Rahat Mahbub Rahat Mahbub - 3 months ago 12
Python Question

Share a variable between two files?

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

file1.py:

def getStatus():
print status


file2.py:

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

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.

notglobal.py:

status = 0

get.py:

import notglobal

def getStatus():
    return notglobal.status

Testing:

>>> import notglobal
>>> import get
>>> notglobal.status = 5
>>> get.getStatus()
5
>>> notglobal.status = 1
>>> get.getStatus()
1
Comments