global, globals(), _global ?

Xaver Hinterhuber xaver.hinterhuber at web.de
Wed Mar 15 05:11:12 EST 2006


Hi Robert,

I was using global variables some time ago, too.
But with the time the program simply got unmaintainable, because it is very 
hard
to trace, why a global variable has some special value and not the one, you 
thought it should have.
So I redesigned the program and now I can do it without global variables.

To me global variables are now in most cases a sign of bad design.
Is there no other way to do it?

Greets

Xaver

"robert" <no-spam at no-spam-no-spam.com> schrieb im Newsbeitrag 
news:dv8oqe$1cbn$1 at ulysses.news.tiscali.de...
> 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