How do you access a variable defined by other modules user input? - python

I am writing a program: prog1 which is importing another module to define a variable.
It works like so:
import modulename1
var1 = attribute1 #situated in modulename1
import modulename2
var2 = attribute2()
function2(var1): # Imagine this being a api call with var1 part of url
#api call
return response.text
function3(function2(var1)+ var2)
modulename1:
attribute1 = input('user value')
modulename2:
def attribute2():
from prog 1 import var 1
atr2 = function(var1) + 'word' #Imagine the function as an api call at
return atr2 #this space
modulename1 accepts user input to define the variable attribute1.
now another module: modulename2 needs to import the var1 with the value from modulename1.
It can´t however import directly from modulename1 as prog 1 is the program launched by the User and importing modulename1 again could result in different user input.
modulename2 in Turn processes var1 and defines attribute2.
var2 is then used in prog1 again. Is there any way to do that?
conditions
Both modules have to be imported completely.
for obvious reasons modulename2 shouldn´t import modulename1

Related

Python - Pass a variable in a module to a function in another module

I have some code in multiple files like so:
A main module:
import TC1
import TC2
Some test case modules, which look like:
testcase = "Test Case 1"
successmessage = "Specific Success Message for Test Case 1"
errormessage = "Specific Error Message for Test Case 1"
# Run test
if pageLoaded == pageExpected:
testresult = 0
logresults()
else:
testresult = 1
logresults()
And a log results module:
def logresults():
print("Test Results for", testcase,)
if testresult == 0
print(testcase, "Passed with", successmessage)
else:
print(testcase, "Failed with", errormessage)
How can I pass variables from each test case to logresults, and have it print the results of each test case as it is run?
I see two issues with your code.
First, if you import a module with a function that works on globals, it will search for globals that share a namespace. For example, if you have a logresultsmodule with a function logresults and you import it, it will only run on variables that look like this: logresultsmodule.variable
To fix this problem, you will have to change the signature of the function to
def logresults(testresult, testcase, successmessage, errormessage): ...
and pass the corresponding variables.
The second problem is you call logresults inside a conditional where there is a chance that the testresult variable hasn't been defined yet.
First evaluate the conditional, and then call logresults.
from logresultsmodule import logresults
{code that defines testcase, successmessage, errormessage}
if pageLoaded == pageExpected:
testresult = 0
else:
testresult = 1
logresults(testresult, testcase, successmessage, errormessage)
So now whenever you import a testcase, the code will run automatically and print the result message.

How to call a variable from other file in python?

I have created 2 files.
a.py has a class foo() and b.py has a class fun(). fun() is a child class of foo().
foo() has a function given below:
def get_random_password(self):
" func to generate random password "
try:
password_characters = string.ascii_letters + string.digits + string.punctuation
nw_password = ''.join(random.choice(password_characters) for i in range(30))
return nw_password
now i want to use this nw_password variable in some other function of fun() ( given below function is used for user login)
username = self.driver.find_element_by_id("username")
time.sleep(3)
username.send_keys(self.vm_spec_dic['name'])
time.sleep(5)
password = self.driver.find_element_by_id("password")
time.sleep(5)
password.send_keys(nw_password)
time.sleep(10)
login = self.driver.find_element_by_id("loginBtn")
login.click()
I am using selenium to automate. I want to call variable nw_password from a.py to b.py. but getting error? I am getting errors like module 'lib.b' has no attribute 'nw_password' ????
from a import nw_password
Importing is not working
The scope of the variable is only inside the function definition, you could probably use a variable and store the return of the get_random_password(self) method
var = yourObjectFromfoo.get_random_password()
then try to import that var
To import your function try this:
from a import get_random_password
If you want to save it to a variable called nw_password you can do this in you main file:
nw_password = get_random_password()
nw_password is just the name of your returned value you're not storing it anywhere. So to get the random password you have to actually run the function you created. And as others have said the variable would be inside the function scope anyway so you would have to make it a global variable (not recommended).

Is there any way to access variable in one function of a file to another file

I have 2 files prgm.py and test.py
1.prgm.py
def move(self)
H=newtest.myfunction()
i= H.index(z)
user=newuser.my_function()
print(user[i])
How will i get user[i] in the other code named test.py
Use an import statement in the other file;
Like this - from prgm import move
Note: For this to work both of the files needs to be in the same folder or the path to the file you are importing needs to be in your PYTHONPATH
Instead of printing the result, you can simply return it. In the second file, you just import the function from this source file and call it.
Given the situation, move is actually a class method, so you need to import the whole class and instance it in the second file
prgm.py
class Example:
def move(self):
H = newtest.myfunction()
i = H.index(z)
user = newuser.my_function()
return user[i]
test.py
from prgm import Example
example = Example()
user = example.move()
# do things with user

Python mock launches whole program instead of substituting input to specific method

I have a program, like:
module "Main":
import SymbolCalculator as sc
# Defining constants:
TEXT_INTRO = sc.TEXT_INTRO
TEXT_INVITE = "Please print any sentence below:\n"
sentence = ""
# Printing introduction to the program:
print TEXT_INTRO
def getting_result():
# Getting input string from console
sentence = sc.get_input_from_prompt(TEXT_INVITE)
# Forming result list via methods defined in SymbolCalculator module
return sc.characters_calculator(sentence)
result_list = getting_result()
# Computing summary via method defined in SymbolCalculator module
sc.printing_summary(sentence, result_list)
# Printing tuples with characters and their occurrences raw-by-raw
sc.printing_list(result_list)
raw_input("Please press any button to quit the program.")
print 'Bye!!!'
And I'm trying to create a simple unit test with mocked raw_input (updated):
from unittest import TestCase, main
from mock import patch
from Ex_41_42_SymbolCalculatorMain import getting_result
class Ex_4a1_SymbolCalculatorUnitTestWMock(TestCase):
##patch ('Ex_41_42_SymbolCalculator.get_input_from_prompt', return_value = 'aabc')
def test_valid_input(self):
with patch('__builtin__.raw_input', return_value = 'aaabbc') as _raw_input:
self.assertEqual(getting_result(), [('a', 3), ('b', 2), ('c', 1)])
_raw_input.assert_called_once_with('Please print any sentence below:\n')
#patch ('Ex_41_42_SymbolCalculator.get_input_from_prompt', return_value = '')
def test_empty_input(self, mock):
self.assertEqual(getting_result(), [])
if __name__ == "__main__":
main()
As well I tried to go via decoration of the tested method by itself, like:
...
#patch ('Ex_41_42_SymbolCalculator.get_input_from_prompt', return_value = 'aabc')
...
My problem is that when I launch the test, all the "Main" module runs at the moment of getting_result method calling. So it starts from the very beginning, asks me to make an input via command prompt, etc. Thus not only test, but the whole regular program is running.
While I'm expecting that only getting_result method is called being provided with return_value.
Please advise.
When you import a module, all the code in the module is run. It doesn't matter that you used from Ex_41_42_SymbolCalculatorMain import getting_result instead of import Ex_41_42_SymbolCalculatorMain; you're still importing the module. There's no way to just "get" one function without executing the rest of the code in the module.
Instead, you should put that code in a function, and then call it from within an if __name__ == "__main__" block, like this:
def getting_result():
# Getting input string from console
sentence = sc.get_input_from_prompt(TEXT_INVITE)
# Forming result list via methods defined in SymbolCalculator module
return sc.characters_calculator(sentence)
def do_stuff():
print TEXT_INTRO
result_list = getting_result()
# Computing summary via method defined in SymbolCalculator module
sc.printing_summary(sentence, result_list)
# Printing tuples with characters and their occurrences raw-by-raw
sc.printing_list(result_list)
raw_input("Please press any button to quit the program.")
print 'Bye!!!'
if __name__ == "__main__":
do_stuff()
Then do_stuff() will only be run if you execute that file directly, not if you import it. This will allow you to import the module without running the stuff in do_stuff. You can learn more about the __main__ business by searching this site for zillions of questions about it (such as this one).

How to set dynamic global variables in Python?

Let's say I've a file a.py and a has a variable var.
In file b.py, I imported, a.py and set a.var = "hello".
Then I imported a.py in c.py and tried to access a.var but I get None.
How to reflect the change in data? It is obvious that two different instances are getting called, but how do I change it?
Edit:
What I am trying to do here is create a config file which constitutes of this:
CONFIG = {
'client_id': 'XX',
'client_secret': 'XX',
'redirect_uri': 'XX'
}
auth_token = ""
auth_url = ""
access_point = ""
Now, let's say I use config.py in the script a.py and set config.access_point = "web"
So, if I import config.py in another file, I want the change to reflect and not return "".
Edit:
Text file seems like an easy way out. I can also use ConfigParser module. But isn't it a bit too much if reading form a file needs to be done in every server request?
As a preliminary, a second import statement, even from another module, does not re-execute code in the source file for the imported module if it has been loaded previously. Instead, importing an already existing module just gives you access to the namespace of that module.
Thus, if you dynamically change variables in your module a, even from code in another module, other modules should in fact see the changed variables.
Consider this test example:
testa.py:
print "Importing module a"
var = ""
testb.py:
import testa
testa.var = "test"
testc.py:
import testa
print testa.var
Now in the python interpreter (or the main script, if you prefer):
>>> import testb
Importing module a
>>> import testc
test
>>>
So you see that the change in var made when importing b is actually seen in c.
I would suspect that your problem lies in whether and in what order your code is actually executed.
In file a.py define a class:
class A:
class_var = False
def __init__(self):
self.object_var = False
Then in b.py import this and instantiate an object of class A:
from a import A
a = A()
Now you can access the attributes of the instance of a.
a.object_var = True
And you can access variables for the class A:
A.class_var = True
If you now check for:
a.class_var
-> True
a.object_var
-> True
another_instance = A()
another_instance.object_var
->False
another_instance.class_var
->True
well , i'd use an text file to set values there,
a.py :
with open("values.txt") as f:
var = f.read()#you can set certain bytes for read
so whenever you import it , it will initialise new value to the var according to the values in the text file , and whenever you want to change the value of var just change the value of the text file

Categories

Resources