Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 902
badatthings Avatar asked Apr 10 '13 11:04

badatthings


1 Answers

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
like image 192
bruno desthuilliers Avatar answered Sep 18 '22 16:09

bruno desthuilliers