Python 2.6 Global Variables

AK Eric warpcat at sbcglobal.net
Fri Oct 30 12:01:34 EDT 2009


> > It isn't a neat trick anymore once you realize the name '__main__'
> > isn't special.
>
> > Replace __main__ with foo, or config, or whatever, and you get the
> > same results. Ok, there is a catch: a file with that name must exist,
> > at least an empty one...

True.  I do feel a bit less special now :-P  And again, I think there
is a difference from saying you *can* work a certain way, and you
*should* work a certain way.  Making a 'global module' you import and
muck with = good.  Other ways discussed = bad (for the most part).
But I think it's important to understand the underlying system
especially when one is first learning:  I hand a heck of a time having
someone explain this stuff to me when I was learning the basics (and
I'm still figuring it out, even from this thread) and now that I get
how it works (I uh... think) it makes me a stronger scripter.  The
common thought seemed to be "you shouldn't do it that way, so I'm not
going to explain it to you" which I've always found quite
frustrating.  And along those lines...

Should we start talking about how you can add stuff to __builtin__ and
then it really is exposed to everything? (right, unless I'm missing
some other Python idiom?)  Again, *not advocating* in standard
practice, but I think it's important to understand how it works.
(ducks incoming flak)

#---------------------
# moduleA.py
import __builtin__
__builtin__.spam = 42
__builtins__["ham"] = 24

#---------------------
# moduleB.py
# This will fail if moduleA isn't executed first
print spam, ham

>>> import moduleA
>>> import moduleB
42 24




More information about the Python-list mailing list