modifying locals
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Oct 31 03:53:10 EDT 2008
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.
--
Steven
More information about the Python-list
mailing list