Access to global variables from a function in an imported module

I have a function that I call from a module. Inside the function, the two variables that I am trying to get become global. When I run the module in IDLE on its own, I can access the variables after the function completes, as expected. When I call a function in the code into which I imported the module, I cannot 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? ")) 

Exit when I run it myself.

 >>> globaltest() What is your name? tom What is your age? 16 >>> name 'tom' >>> age 16 

And the code into which to import it.

 import name_age name_age.globaltest() 

but when I start an attempt to access the variables in the code where I 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 to make a global variable in the code where I imported the module, or to access the variables "name" or "age" in this function.

+6
source share
2 answers

The simple answer is "do not." Python โ€œglobalsโ€ are only global globules at the module level, and even global globules at the module level (mutable global global module levels) should be avoided as much as possible, and very few of them.

The right decision is to learn how to use function parameters and return values โ€‹โ€‹correctly. In your case, the 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 
+3
source

Just change the import statement to this:

 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 operator, you need to access your global variables using a link to the module name, namely:

Example:

 In [1]: import name_age In [2]: print name_age.name Out[2]: 'tom' 
+1
source

All Articles