updating locals() and globals() (WAS: How do I do this? (eval() on the left hand side))
Caleb Hattingh
caleb1 at telkomsa.net
Wed Dec 8 21:59:21 EST 2004
Steve,
I don't think I understand. Here is what I just tried:
'>>> def f():
x = 3
d = locals()
print x
print d['x']
d['x'] = 5
print x
'>>> f()
3
3
3
'>>>
In your example, x had not yet been initialised, maybe. What I am seeing
is that "x" does not seem to update when being assigned to - I guess this
is what you are referring to by being unreliable.
But "unreliable" sounds kinda vague and intermittent, and I assume that is
not the case here - What is the Rule(tm)?
Thanks
Caleb
On Wed, 08 Dec 2004 16:59:23 GMT, Steven Bethard
<steven.bethard at gmail.com> wrote:
> Peter Hansen wrote:
>> Nick Coghlan wrote:
>>
>>> Generally, altering the contents of the dicts returned by locals() and
>>> globals() is unreliable at best.
>> Nick, could you please comment on why you say this about globals()?
>> I've never heard of any possibility of "unreliability" in updating
>> globals() and, as far as I know, a large body of code exists which
>> does in fact rely on this -- much of mine included. ;-)
>
> Updating locals() is unreliable. Updating globals() is fine, AFAIK.
>
> http://docs.python.org/lib/built-in-funcs.html
>
> I believe that the only time that locals() is updatable is when locals()
> is globals():
>
> >>> locals() is globals()
> True
> >>> x
> Traceback (most recent call last):
> File "<interactive input>", line 1, in ?
> NameError: name 'x' is not defined
> >>> locals()['x'] = 3
> >>> x
> 3
>
>
> >>> def f():
> ... print locals() is globals()
> ... locals()['x'] = 3
> ... print x
> ...
> >>> f()
> False
> Traceback (most recent call last):
> File "<interactive input>", line 1, in ?
> File "<interactive input>", line 4, in f
> NameError: global name 'x' is not defined
>
>
> Steve
More information about the Python-list
mailing list