Today I found out that Python caches the expression {}and replaces it with a new empty dict when it is assigned to a variable:
print id({})
print id({})
x = {}
print id(x)
print id({})
I did not look at the source code, but I have an idea how this can be implemented. (Perhaps when the global reference count is {}incremented, the global {}is replaced.)
But consider this bit:
def f(x):
x['a'] = 1
print(id(x), x)
print(id(x))
f({})
print(id({}), {})
print(id({}))
fmodifies the global dict without causing it to be replaced, and prints the modified dict. But outside f, even though the id is the same, the global dict is now empty!
What's happening?
source
share