Access global variables from a function in an imported module
Solution 1
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
Solution 2
Just change your import
statement to this one:
from name_age import *
example:
In [1]: from name_age import *
In [2]: print name
Out[2]: '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:
example:
In [1]: import name_age
In [2]: print name_age.name
Out[2]: 'tom'
Admin
Updated on June 17, 2022Comments
-
Admin almost 2 years
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.
-
bruno desthuilliers about 11 yearsstar imports are about as evil as globals. @badathings: dont do this.
-
SiHa almost 10 yearsFrom PEP8 "Wildcard imports (from <module> import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools..."
-
variable over 4 yearsDo you know if there is any documentation about this concept with pictorial representation of the frames (example: function call stack frame)?
-
variable over 4 yearsDo you know if there is any documentation about this concept with pictorial representation of the frames (example: function call stack frame)?
-
variable over 4 yearsPython globals, module frame, stack frame.
-
bruno desthuilliers over 4 years@variable nope, no idea.
-
Thanasis Petsas over 4 years@variable Sorry I am not aware of anything like that.
-
Harlan Nelson over 2 yearsSometime "simple" is not enough. What if a function is going to do something that ties up resources and I want to be able to ask it to check first. So I create a global variable that lets me signal permission to the function. The permission variable is then modified globally.
-
bruno desthuilliers over 2 years@HarlanNelson there are indeed valid use case for per-session or per-user etc application-level state management - and here the "do's and dont's" varies depending on the context (shared multi-process web-server side apps and single-user GUI apps have quite different constraints for example). BUT your domain / library code should still NOT be aware of this nor depend on global state, this belongs to the application/UI layer. In your case, you could use a "permission" decorator to wrap the inner function and let the decorator take care of the user session's specifics...
-
Harlan Nelson over 2 years@bruno-desthuilliers. Thanks, I need to figure out how to do that.
-
bruno desthuilliers over 2 years@HarlanNelson quite simply move all the user interactions / permissions / etc outside the function itself, and move it in the UI layer part that's responsible for calling (or not !) the core function. How and where you store the "permission" flag etc is up to you (in a web app this will typically be in a session tied to a session cookie), but it's always better to wrap all this into a dedicated "session" or "settings" object (singleton or borg patterns come to mind here) instead of directly accessing globals. This will make your code easier to test and maintain.