Global variables aren’t global in Python

George Shuklin
Python Pandemonium
Published in
1 min readMay 18, 2017

… 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:

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.

--

--

George Shuklin
Python Pandemonium

I work at Servers.com, most of my stories are about Ansible, Ceph, Python, Openstack and Linux. My hobby is Rust.