Rahat Mahbub Rahat Mahbub - 1 year ago 105
Python Question

Share a variable between two files?

What is a mechanism in Python by which I can do the following:


def getStatus():
print status


status = 5
getStatus() # 5
status = 1
getStatus() # 1

The function and the variable are in two different files and I'd like to avoid the use of a global.

Answer Source

You can share variables without making them global by putting them in a module. Anybody who imports the module gets the same module object, so its contents are shared; changes made at one location show up in all the others.


status = 0


import notglobal

def getStatus():
    return notglobal.status


>>> import notglobal
>>> import get
>>> notglobal.status = 5
>>> get.getStatus()
>>> notglobal.status = 1
>>> get.getStatus()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download