global, globals(), _global ?
robert
no-spam at no-spam-no-spam.com
Wed Mar 15 05:03:56 EST 2006
Using global variables in Python often raises chaos. Other languages use
a clear prefix for globals.
* you forget to declare a global
* or you declare a global too much or in conflict
* you have a local identical variable name and want to save/load it
to/from the global with same name
* while you add code, the definition of globals moves more and more
apart from their use cases -> weirdness; programmers thinking is fragmented
* using globals()['xy'] is 'stringy non-program-code'
Thus, since long time at the head of my bigger modules I often put...
_global = sys.modules[__name__]
...and use global variables only/mainly like
def f(y):
v=x=_global.x
_global.y=y
...
for me this method is much more clear overall. And it is in line with
the clear exposition of "self" as regular object in Python methods (in a
much more self-similiar way compared to frozen @ $ m_... hacks in other
languages)
I know, this home created _global creates a circular ref, but usually
this is not serious as modules are unload only at the end of a program.
( side question: does this maybe hinder global objects from being
__del__'ed correctly; is at least gc() run when all modules are pulled
off at exit() )
Somehow I miss a nice standard method for using globals in an
unfragmented way everywhere. What do you think?
Robert
More information about the Python-list
mailing list