How do I do this? (eval() on the left hand side)

Caleb Hattingh caleb1 at telkomsa.net
Wed Dec 8 22:31:11 EST 2004


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 <__peter__ at web.de> 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
>




More information about the Python-list mailing list