So, I’m confused. I have a module containing some function that I use in another module. Imported like so:
from <module> import *
Inside my module, there exist functions whose purpose is to set global variables in the main program.
main.py:
from functions import *
bar = 20
print bar
changeBar()
print bar
functions.py:
def changeBarHelper(variable):
variable = variable * 2
return variable
def changeBar():
global bar
bar = changeBarHelper(bar)
Now, this is a simplification, but it is the least code that yields the same result:
Traceback (most recent call last):
File "/path/main.py", line 5, in
changeBar()
File "/path/functions.py", line 7, in changeBar
bar = changeBarHelper(bar)
NameError: global name 'bar' is not defined
Doing an
import *in the way that you’ve done it is a one way process. You’ve imported a bunch of names, much the same way as you’d do:So they are all just assigned to names in the global scope of the module where the
importis done. What this does not do is connect the global namespaces of these two modules.globalmeans module-global, not global-to-all-modules. So every module might have its ownfubarglobal variable, and assigning to one won’t assign to every module.If you want to access a name from another module, you must import it. So in this example:
By doing the import inside the function itself, you can avoid circular imports.