[Python-Dev] Should vars() return modifiable dict?

Serhiy Storchaka storchaka at gmail.com
Wed Oct 3 10:54:28 CEST 2012


For objects with __dict__ vars() returns modifiable dict:

 >>> class A():
...     pass
...
 >>> a = A()
 >>> a.x = 42
 >>> vars(a)
{'x': 42}
 >>> vars(a)['x'] = 43
 >>> vars(a)['y'] = 44
 >>> a.x, a.y, vars(a)
(43, 44, {'y': 44, 'x': 43})

For globals vars() returns modifiable dict:

 >>> x = 42
 >>> vars()['x']
42
 >>> vars()['x'] = 43
 >>> vars()['y'] = 44
 >>> vars()['x'], vars()['y']
(43, 44)

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?

Should vars() for objects with __slots__ [1] returns modifiable or 
non-modifiable dict?

[1] http://bugs.python.org/issue13290



More information about the Python-Dev mailing list