[Python-Dev] Should vars() return modifiable dict?
Steven D'Aprano
steve at pearwood.info
Wed Oct 3 17:34:33 CEST 2012
On 03/10/12 18:54, Serhiy Storchaka wrote:
> For locals vars() returns... hmm, partially modifiable dict:
>
>> >> def f():
> ... x = 42
> ... print(vars())
> ... vars()['x'] = 43
> ... vars()['y'] = 44
> ... print(x, vars())
> ...
>> >> f()
> {'x': 42}
> 42 {'y': 44, 'x': 42}
>
> Should behavior of vars() be corrected for locals?
I believe you are misinterpreting what you are seeing. In this case,
vars() simply returns locals(), which is an ordinary dict, but changes
to that dict are not guaranteed to propagate to the actual local
variables themselves. You make changes to that dict, then call vars()
again, which returns a fresh locals() dict. So what you are seeing is
simply a side-effect of the fact that changes to locals() may not
actually effect the local variables.
Note that in IronPython, the behaviour of your code is different:
steve at runes:~$ ipy
IronPython 2.6 Beta 2 DEBUG (2.6.0.20) on .NET 2.0.50727.1433
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
... x = 42
... print(vars())
... vars()['x'] = 43
... vars()['y'] = 44
... print(x, vars())
...
>>> f()
{'x': 42}
(43, {'y': 44, 'x': 43})
> Should vars() for objects with __slots__ [1] returns modifiable or non-modifiable dict?
>
> [1] http://bugs.python.org/issue13290
You are assuming that the behaviour of vars(obj) should change. I don't think
that is necessarily the case.
vars(obj) is defined as returning the object __dict__ attribute. If an object
has no __dict__, vars() should (pick one):
1) Keep the current behaviour and raise an exception.
2) Return a regular dict containing {slot: value} for each of the slots.
Since the dict is a copy, changes to the dict will not effect the
original object.
3) Return a dictproxy containing {slot: value} for each of the slots.
Since the dictproxy does not support item assignment, you can't
modify it.
4) Return some other proxy object such that changes to the dict will
also change the object's slot attributes.
I find myself unable to choose between 2) and 4), which suggests that
the status quo wins and we keep the current behaviour.
--
Steven
More information about the Python-Dev
mailing list