Thx Peter

I verified this situation myself with a post from Steven Bethard earlier (trying to use "locals" within a function definition).

I am convinced now that locals() doesn't work as (I) expected. Steven says there was some or other reason why locals() as used in this context is not writable - Do you know why this is? I really do not like guidelines like "may not work", "is unreliable" and so on. Perhaps this is a character flaw, but I really do like to know what works, when it works, and when it doesn't work.

In this scenario, we can see it doesn't work. To my eyes, it doesn't work *in the way I expect* (which is highly subjective, no argument there). Would this be a situation where it would be nice to have an exception thrown if locals() is assigned to in a scope where it is not writable?

It would also be nice if globals and locals behaved the same, differing only in scope (which is what I expected originally anyway). But we can't have everything, I guess :)

Caleb


On Wed, 08 Dec 2004 20:49:53 +0100, Peter Otten <[EMAIL PROTECTED]> wrote:

Caleb Hattingh wrote:

In what way is it unreliable?ÃÂÃÂIÃÂcan'tÃÂseemÃÂtoÃÂcreateÃÂaÃÂsituationÃÂwhere
the update through globals and locals doesn't work.ÃÂÃÂÃÂAreÃÂyouÃÂreferring

Updates to a locals() dictionary may not be reflected by the variables in the local scope, e. g.:

def f():
...     locals()["a"] = 1
...     print a
...
f()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in f
NameError: global name 'a' is not defined
def f():
...     a = 42
...     locals()["a"] = 1
...     print a
...
f()
42

Updating globals() should be safe.
Peter


-- http://mail.python.org/mailman/listinfo/python-list

Reply via email to