modifying locals

M.-A. Lemburg mal at egenix.com
Fri Oct 31 06:17:37 EDT 2008


On 2008-10-31 09:08, Tino Wildenhain wrote:
> Hi,
> 
> Steven D'Aprano wrote:
>> On Fri, 31 Oct 2008 07:10:05 +0100, Tino Wildenhain wrote:
>>
>>> Also, locals() already returns a dict, no need for the exec trickery.
>>> You can just modify it:
>>>
>>>  >>> locals()["foo"]="bar"
>>>  >>> foo
>>> 'bar'
>>>
>>
>> That is incorrect. People often try modifying locals() in the global
>> scope, and then get bitten when it doesn't work in a function or class.
> 
>>
>>>>> def foo():
>> ...     x = 1
>> ...     locals()['y'] = 2
>> ...     y
>> ...
>>>>> foo()
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>>   File "<stdin>", line 4, in foo
>> NameError: global name 'y' is not defined
>>
>> You cannot modify locals() and have it work. The fact that it happens
>> to work when locals() == globals() is probably an accident.
> 
> 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 ?

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Oct 31 2008)
>>> Python/Zope Consulting and Support ...        http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________

:::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! ::::


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611



More information about the Python-list mailing list