modifying locals

Tino Wildenhain tino at wildenhain.de
Fri Oct 31 04:08:16 EDT 2008


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 :-)

Cheers
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/9784a7ce/attachment-0001.bin>


More information about the Python-list mailing list