Stagnant Frame Data?
Peter Otten
__peter__ at web.de
Sun Nov 15 11:00:17 EST 2009
Mike wrote:
> I'll apologize first for this somewhat lengthy example. It does
> however recreate the problem I've run into. This is stripped-down code
> from a much more meaningful system.
>
> I have two example classes, "AutoChecker" and "Snapshot" that evaluate
> variables in their caller's namespace using the frame stack. As
> written, the output is not what is expected: the variables evaluate to
> "stagnant" values.
>
> However, if the one indicated line is uncommented, then the result is
> as expected.
>
> So my questions are: Is this a bug in Python? Is this an invalid use
> of frame data? Why does the single line "sys._getframe(1).f_locals"
> fix the behavior?
A simplified demonstration of your problem:
>>> def f(update):
... a = locals()
... x = 42
... if update: locals()
... print a
...
>>> f(False)
{'update': False}
>>> f(True)
{'a': {...}, 'x': 42, 'update': True}
The local namespace is not a dictionary, and the locals()/f_locals
dictionary contains a snapshot of the local namespace. Accessing the
f_locals attribute is one way to trigger an update of that snapshot.
What's puzzling is that the same dictionary is reused.
Peter
More information about the Python-list
mailing list