Manipulating caller frame
Lulu of the Lotus-Eaters
mertz at gnosis.cx
Mon Dec 16 23:50:29 EST 2002
bokr at oz.net (Bengt Richter) wrote previously:
|ISTM the key issue is being able to write an abbreviation for something
|to be done more than once **within the current scope**. An ordinary
|function can't do that for several reasons.
Along those lines, the following rather shocks me:
% cat change_foo.py
def change_foo():
import inspect
caller_locals = inspect.currentframe(1).f_locals
caller_locals['foo'] = 'newfoo'
return caller_locals
def somefunc():
baz = 'bat'
foo = 'bar'
print foo
l = change_foo()
print foo
print l, locals()
print id(l), id(locals())
somefunc()
% python change_foo.py
bar
bar
{'foo': 'newfoo', 'baz': 'bat'} {'l': {...}, 'baz': 'bat', 'foo': 'bar'}
584780 584780
I can accept easily enough (if this is so) that 'caller_locals' is
really only a copy of the locals() dictionary. Which would explain why
changing it doesn't change 'foo'.
But what I just can't get my head around is the idea that the 'l' and
'locals()' have the SAME ID, and yet different contents.
Can someone help me here?
Yours, Lulu...
More information about the Python-list
mailing list