Safe to modify globals(), or not?

Terry Reedy tjreedy at udel.edu
Thu Jan 29 21:58:46 EST 2004


"Robert Dodier" <robert_dodier at yahoo.com> wrote in message
news:6714766d.0401291559.45413e0d at posting.google.com...
> Hello,
>
> I'm interested in introducing new variables into the environment
> of a Python interpreter or program.

This is a bit vague and not obviously connected to your question.  Let's
ignore this.
Globals() returns the module-specific 'global' namespace, as opposed to the
function-local namespace.

> In reading through old posts to this newsgroup, I see there is
> an often-repeating warning against modifying the contents of locals().

Outside of functions, locals() == globals().  Inside of functions, where
locals() != globals() and is therefore not redundant and potentially
useful, the result is only guaranteed to be a read-only *copy* of the
current state of the local namespace.  Even if it is writable, the changes
may only change the *copy* and not the local namespace itself.  This makes
for subtle bugs when the programmer expects (if falsely) that changes are
propagated.

> Fair enough. However, is there anything wrong with modifying globals()

No.  "globals()['a'] = 3" is exactly the same as "a=3" executed at module
scope, outside of functions.  The purpose is to allow you to set a variable
whose name you do not know until runtime.  An example, as in your
application, is when the name comes from user input.

Having said that, you do need to ask yourself whether you really want to
put user variables in the global namespace that your are using yourself for
your code, which will wreck havoc when there is a name collision.  Or
whether you should put them is a separate namespace dict such as uservars.
And then exec user code with uservars as the globals.  Or something like
that.

Terry J. Reedy







More information about the Python-list mailing list