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

Steven D'Aprano steve at pearwood.info
Fri Oct 5 15:47:12 CEST 2012


On 05/10/12 22:58, Nick Coghlan wrote about locals():

As for why changes don't get written back, it's because the compiler is allowed to assume it knows about every variable name that exists in the local scope (by design), and that doesn't fit with writable locals() for functions.

And to be clear, that is implementation-dependent. IronPython locals() does write back to local variables.

Trying to modify locals() can lead to some really unintuitive behaviour. For example, in CPython 3.2:

py> def test(): ... x = 1 ... locals()['x'] = 2 # writing to locals has no effect ... locals()['y'] = 3 # except when it does... ... print(x, locals()) ... py> test() 1 {'y': 3, 'x': 1}

-- Steven



More information about the Python-Dev mailing list