Question
Asked By – Dan Homerick
The __debug__
variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?
The variable (let’s be original and call it ‘foo’) doesn’t have to be truly global, in the sense that if I change foo in one module, it is updated in others. I’d be fine if I could set foo before importing other modules and then they would see the same value for it.
Now we will see solution for issue: How to make a cross-module variable?
Answer
I don’t endorse this solution in any way, shape or form. But if you add a variable to the __builtin__
module, it will be accessible as if a global from any other module that includes __builtin__
— which is all of them, by default.
a.py contains
print foo
b.py contains
import __builtin__
__builtin__.foo = 1
import a
The result is that “1” is printed.
Edit: The __builtin__
module is available as the local symbol __builtins__
— that’s the reason for the discrepancy between two of these answers. Also note that __builtin__
has been renamed to builtins
in python3.
This question is answered By – Curt Hagenlocher
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0