alphanumeric
alphanumeric

Reputation: 19329

How to declare global variable that is visible to imported module functions

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)?

to be imported "myModule.py" :

def printX():
    print variableX

def printY():
    global variableY
    variableY='y'
    print variableY

Main Programm

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

Answers (1)

Hai Vu
Hai Vu

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

Related Questions