Writing to locals(), globals(), and vars()

Alex Martelli aleaxit at yahoo.com
Sun Sep 3 09:24:25 CEST 2000

"Michael Haggerty" <mhagger at alum.mit.edu> wrote in message
news:m2aedqqt45.fsf at freak.kaiserty.com...
> First question: Is there a way to write to the local symbol table in a
> generic way (without using `exec')?  For example, this could be used

No, because the compiler optimizes local-namespaces accesses
to reduce the lookups-by-name.  Functions that contain an exec
statement have this important optimization turned off, "just in
case".  So, this happens to currently work...:

def funfun():
    exec 'pass'
    locals()['foo'] = 'bar'
    print foo

while commenting the exec statement has it fail with NameError.

You can consider the statement
    exec 'pass'
as a way of saying "I don't care if this function runs twice as
slow, writing to the local symbol table is what life is truly
all about".  I'm not sure how "solid" this situation is -- does
it depend on deep Python truth, or just a current accident of
implementation?  Maybe someone with deeper understanding
can help on this.

> Second question: Is it legal to write to globals()?  The Library
> Reference is mute on this point.  (Not that it would help with the
> above problem...)

As above: it works, but, who knows how solidly...?  Similarly,
is direct updating of a module's __dict__ guaranteed to work,
or does it just currently happen to...?

Personally, being a coward, I tend to rely on some *instance*'s
__dict__ for this kind of dirty work.  I update() it with vars()
or whatever at __init__ time, then can freely use that instance
to access a mutable set of 'variables'.  And *that* one is (I
think and hope) guaranteed to work and keep working, since
writing into an instance's __dict__ is a documented way to


More information about the Python-list mailing list