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_lan guage("Hey, this is far out, man.") Hey.part_of_spe ech
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 3 2076
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_lan guage("Hey, this is far out, man.") >>> Hey.part_of_spe ech
Interjection
import __main__
tmp = parse_funky_lan guage("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**@pythoncra ft.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
"Robert Dodier" <ro***********@ yahoo.com> wrote in message
news:67******** *************** ***@posting.goo gle.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
Aahz wrote: import __main__ tmp = parse_funky_lan guage("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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 are ignored? I have tried
entering data such as `/bin/date > /tmp/1234` and this does not create a
temporary file (which is what I would expect, meaning that my form is safe).
|
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 a value for 'href', 'desc', and
'info' but when I try to pass one of these "columns" to array_multisort() it
whinges about it not being an array or a sort value :-(
Can PHP not understand arrays stored in $GLOBALS or something?
|
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 (safe) way to
do it?
Thanks!
>>> x=
>>> for t in x:
|
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 tried storing the handle of Window A ( var winHandle = this; )
in a global variable/file ( globals.js ) and then accessing it from
|
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
| |
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 there a script, product or way?
Thanks
|
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.
exec statements are difficult for debuggers to deal with, so as a
workaround I built my code into a function and saved it in a .py file.
The I load the .py file as a module and call the function instead. This
works great, and it has the added...
|
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() printed\n"
|
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) and call
an external program like 'bc' to do the dirty work. I think that this
would avoid someone from embedding os.system("rm ...") in what I thought
would be a math expression and having it maybe do damage? Perhaps I'm
getting too paranoid in...
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| | |