modifying locals
Tino Wildenhain
tino at wildenhain.de
Fri Oct 31 06:51:17 EDT 2008
M.-A. Lemburg wrote:
> On 2008-10-31 09:08, Tino Wildenhain wrote:
...
>> Ah thats interesting. I would not know because I usually avoid
>> such ugly hacks :-)
>
> It doesn't even work for already defined local variables:
>
>>>> def foo():
> ... x = 1
> ... locals()['x'] = 2
> ... print x
> ...
>>>> foo()
> 1
>
> The reason is that locals are copied in to a C array
> when entering a function. Manipulations are then
> done using the LOAD_FAST, STORE_FAST VM opcodes.
>
> The locals() dictionary only shadows these locals: it copies
> the current values from the C array into the frame's
> f_locals dictionary and then returns the dictionary.
>
> This also works the other way around, but only in very
> cases:
>
> * when running "from xyz import *"
> * when running code using "exec"
>
> globals() on the other hand usually refers to a module
> namespace dictionary, for which there are no such
> optimizations..
>
> I don't know of any way to insert locals modified in
> a calling stack frame... but then again: why would you
> want to do this anyway ?
Yes, thats what I'm saying. Unless you are writing a
debugger or something you better don't mess with the
internals.
Regards
Tino
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3241 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20081031/28b4f05b/attachment-0001.bin>
More information about the Python-list
mailing list