Safe to modify globals(), or not?
Aahz
aahz at pythoncraft.com
Thu Jan 29 21:01:05 EST 2004
In article <6714766d.0401291559.45413e0d at posting.google.com>,
Robert Dodier <robert_dodier at yahoo.com> wrote:
>
>In reading through old posts to this newsgroup, I see there is
>an often-repeating warning against modifying the contents of locals().
>Fair enough. However, is there anything wrong with modifying globals()
>?
Not wrong, exactly, but there may well be in the future, and there are
better ways currently.
>By the way, is there another way to introduce a new variable into
>a scope (local or global) other than assigning directly to the
>dictionary returned by locals() or globals() ?
For locals, it's a lot trickier, but you're less likely to want to do
that.
>Just some context -- I want to parse strings written in a
>"little language" and then have new variables show up in the Python
>environment so the user can manipulate them. E.g.,
>
> >>> parse_funky_language("Hey, this is far out, man.")
> >>> Hey.part_of_speech
> Interjection
import __main__
tmp = parse_funky_language("Hey, this is far out, man.")
setattr(__main__, tmp.name, tmp.value)
In the context of the interactive interpreter, it's a bit harder to do;
I don't remember off-hand what the namespace of the interpreter is.
--
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
"The joy of coding Python should be in seeing short, concise, readable
classes that express a lot of action in a small amount of clear code --
not in reams of trivial code that bores the reader to death." --GvR
More information about the Python-list
mailing list