updating locals() and globals() (WAS: How do I do this? (eval() on the left hand side))
Steven Bethard
steven.bethard at gmail.com
Wed Dec 8 15:13:12 EST 2004
Caleb Hattingh wrote:
> 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.
Yes, that was my intent. In the same way that my "x" was not
initialized, your "x" is not updated. locals() is readable but not
writable in any case where locals() is not globals(), I believe.
> But "unreliable" sounds kinda vague and intermittent, and I assume that
> is not the case here - What is the Rule(tm)?
Unfortunately, I don't think there is a Rule(tm) because the behavior of
locals() (and globals()?) are implementation details. I remember
hearing an explanation of why locals() is not writable that had to do
with something about efficiency and the call stack (or something like
that)...
Steve
More information about the Python-list
mailing list