473,386 Members | 1,883 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Safe to modify globals(), or not?

Hello,

I'm interested in introducing new variables into the environment
of a Python interpreter or program.

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()
?

In the list of built-in functions
(http://www.python.org/doc/lib/built-in-funcs.html)
locals() has an explicit warning, globals() doesn't. Does that mean
it's safe to modify globals() ?

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() ?

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

Any light you can shed on this issue will be appreciated.
Thanks for not getting distracted about whether this is useful.

regards,
Robert Dodier
--
If I have not seen as far as others, it is because
giants were standing on my shoulders. -- Hal Abelson
Jul 18 '05 #1
3 2062
In article <67**************************@posting.google.com >,
Robert Dodier <ro***********@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 (aa**@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
Jul 18 '05 #2

"Robert Dodier" <ro***********@yahoo.com> wrote in message
news:67**************************@posting.google.c om...
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


Jul 18 '05 #3
Aahz wrote:
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.


You don't need to :-)

Python 2.3.3 (#1, Jan 3 2004, 13:57:08)
[GCC 3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
__name__

'__main__'

Peter
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Reply Via Newsgroup | last post by:
Folks, I am using Apache 1.3.x with PHP 4.3.x and MySQL v4. Short question: Before I put my web form available on the internet, how can I test it from mis-use in such that special characters...
5
by: Frostillicus | last post by:
I'm trying to use array_multisort to sort by one of the dimensions of an array stored in $GLOBALS like this: array_multisort($GLOBALS, SORT_STRING, SORT_DESC); Each "row" in $GLOBALS contains...
4
by: Phil Schmidt | last post by:
The following example works fine (Python 2.3), but is it always safe to modify a list that is being iterated in a loop, regardless of the actual contents of the list x? If not, what's a better...
2
by: Juan Garcia | last post by:
Subject says it all. Given: Window A with text field. Window B with a button (onClick opens Window C) Window C with a button (onClick I want it to modify text fields of Window A) I have...
9
by: Andy Chang | last post by:
Hi, If I have this function void DoSomething(int& index) { ::Sleep(10000); DoSomethingWith(index); } Is the variable index thread safe? Meaning that if I call this from two
1
by: goldtech | last post by:
Is there a way to create thumnails with a script in PHP with safe mode ON? We want to keep safe mode ON for our server but beable to automatically create thumbs from full size image files. Is...
5
by: Sandra-24 | last post by:
Is there a way in python to add the items of a dictionary to the local function scope? i.e. var_foo = dict. I don't know how many items are in this dictionary, or what they are until runtime. ...
1
by: cokofreedom | last post by:
if __name__ == '__main__': print "Globals (For Loop):" try: for i in globals(): print "\t%s" % i except RuntimeError: print "Only some globals() printed\n" else: print "All globals()...
7
by: bvdp | last post by:
I'm finding my quest for a safe eval() quite frustrating :) Any comments on this: Just forget about getting python to do this and, instead, grab my set of values (from a user supplied text file)...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.