Global variables aren’t global in Python
… they are module-scoped.
Python, while been a very pleasant language to write, occasionally cause me some head-scratching.
I have module for tests which have a bug. This bug require a workaround in the code, which is 5 modules deep from the test. In my test I decided to use some global variable to signal this. It was precisely the case for global variable. I set up it in my test routine, and it will affect some deeply nested code in my application.
But it didn’t work. After some fingerpointing to py.test-messing-with-variables I created simple module with a function which prints globals()
and other module which calls first one after setting a global variable. I found that global variables which are set in one module aren’t available in others.
I dug into documentation:
- https://docs.python.org/2/library/functions.html#globals
- https://docs.python.org/3/reference/simple_stmts.html#global
- https://docs.python.org/3/reference/executionmodel.html#resolution-of-names
- https://docs.python.org/2/faq/programming.html
None of it have clear explanation about non-global scope for global
.
By trial and error I found that global variables are stored in the module-scoped dictionary.
Conclusion
Python uses global
to reference to module-global variables. There are no program-global variables in Python.
P. S. For my case with tests, I was forced to use full path specification with many dots to make a monkey patch.