Reputation: 19329
Any global
variable declared inside of imported .py module remains to be global "within" its own module and it is global "within" a script or a program to where this module was imported (using Python import
command).
Now what if after importing a module X
I declare a global variable Y
. And I want to make a variable Y "visible" or global
to functions defined in the imported module X
(so I don't have to pass Y
to the imported module functions as the argument)?
def printX():
print variableX
def printY():
global variableY
variableY='y'
print variableY
import myModule as myModule
myModule.printY()
print myModule.variableY
global variableX
variableX='X'
print variableX
myModule.printX() # this will result to NameError
myModule.printX()
results to:
NameError: global name 'variableX' is not defined
Upvotes: 4
Views: 711
Reputation: 40733
the function printX
looks for global variableX
within myModule
. That is where you should declare your variable:
import myModule as myModule
myModule.printY()
print myModule.variableY
myModule.variableX = 10
print myModule.variableX
myModule.printX()
Upvotes: 3