You could use my favorite alternative to global
(a pretty idiosyncratic taste...):
import sys
thismodule = sys.modules[__name__]
thismodule.foo = 'bar'
def update_foo():
thismodule.foo = 'baz'
Once you've made the thismodule
reference, you don't need to use global
in this module, because you're always working with qualified names rather than bare names (a much better idea IMHO... but maybe in MHO only, I've not been able to convince Guido to supply thismodule
[[or some other identifier with this functionality]] back when Python 3 was gestating).
Note that the first assignment to foo
, at global level, can be done either with this explicit syntax, or by assigning to barename foo
as you do in your code (I guess it's not surprising that my preference goes to the explicit form, though, in this case, just barely).