How to share a global variable across python modules

published Jun 19, 2014 12:30   by admin ( last modified Jun 28, 2014 03:22 )

How can you have a global object or variable that you can share across modules in python? Each module in python has its own name space and is happily unaware of anything defined in the others' name spaces. You can however import a variable from another name space, and then you can modify that and it will be visible in other modules that do the same. Except that you can't, because now it is in your name space and not the same as what the others have imported. What you can do however is to import the module in which it is defined, and then it gets changed everywhere.

 

Basically this won't work:

from flum import bletch

bletch = 67

That change will not be picked up by any other modules that do the same kind of import.

But this will work:

import flum

flum.bletch = 67

Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:


Read more: Link - How do I share global variables across modules?