[ Access global variables from a function in an imported module ]
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
from module import noglobaltest name, age = noglobaltest() print "name :", name, "age :", age
Just change your
import statement to this one:
from name_age import *
In : from name_age import * In : print name Out: 'tom'
Otherwise, if you want to use the
import name_age statement, then you have to access your
global variables through the module name reference, that is:
In : import name_age In : print name_age.name Out: 'tom'