[Tutor] set locals

Peter Otten __peter__ at web.de
Wed Dec 18 10:02:37 CET 2013


spir wrote:

> Hello,
> 
> is it at all possible to set new vars (or any symbol) into an existing
> scope (typically locals())?

locals() normally contains a copy of the current namespace as a dict. 
Setting items is possible but only alters the dict and has no effect on the 
original namespace:

>>> def f():
...     x = 1
...     namespace = locals()
...     print(namespace)
...     namespace["x"] = 2
...     print(namespace)
...     print(x)
... 
>>> f()
{'x': 1}
{'x': 2}
1

On the module level the local is identical with the global namespace, and 
you can define variables with

>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> locals()["x"] = 42
>>> x
42

In Python 2 you can introduce local variables with exec:

>>> def f():
...     exec 'foo = "bar"'
...     print foo
... 
>>> f()
bar

In Python 3 that is no longer possible:

>>> def f():
...     exec('foo = "bar"')
...     print(locals())
...     print(eval("foo"))
...     print(foo)
... 
>>> f()
{'foo': 'bar'}
bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in f
NameError: name 'foo' is not defined

>      scope[name] = value
> raises by me an error like:
>      TypeError: 'mappingproxy' object does not support item assignment
> 
> I guess 'mappingproxy' is the implementation name of a scope (here,
> local), and I thought scopes were just dicts; so what is the issue? Do you
> see an alternative?

Like Steven I have no idea how you produced the mappingproxy. Are you trying 
to use a class as a namespace (in Python 3.3)?

>>> class A: pass
... 
>>> A.__dict__["foo"] = "bar"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mappingproxy' object does not support item assignment




More information about the Tutor mailing list