I have a function that i'm calling from module. Within the function the two variables i'm trying to access are made global. When I run the module in IDLE by itself I can still access the variables after the function ends, as expected. When I call the function in the code that I have imported the module into I can't access the variables.
#module to be imported
def globaltest():
global name
global age
name = str(raw_input("What is your name? "))
age = int(raw_input("What is your age? "))
The output when I run it by itself.
>>> globaltest()
What is your name? tom
What is your age? 16
>>> name
'tom'
>>> age
16
And the code where import it.
import name_age
name_age.globaltest()
but when I run attempt to access the variables in the code where I have imported it.
What is your name? tom
What is your age? 16
>>> name
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
name
NameError: name 'name' is not defined
>>>
How can I make the variable global in the code where I have imported the module or access the 'name' or 'age' variables in the function.
The simple answer is "don't". Python's "globals" are only module-level globals, and even module-level globals (mutable module-level globals that is) should be avoided as much as possible, and there's really very very few reasons to use one.
The right solution is to learn to properly use function params and return values. In your case a first approach would be
#module.py
def noglobaltest():
name = str(raw_input("What is your name? "))
age = int(raw_input("What is your age? "))
return name, age
and then:
from module import noglobaltest
name, age = noglobaltest()
print "name :", name, "age :", age
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With