Strange behavior related to apparent caching "{}"

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({})
# 40357936

print id({})
# 40357936

x = {}
print id(x)
# 40357936

print id({})
# 40356432

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))
# 34076544

f({})
# (34076544, {'a': 1})

print(id({}), {})
# (34076544, {})

print(id({}))
# 34076544

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?

+5
source share
2 answers

- {} , 0, . , , , . x, , .

, f , dict, , .

+6

Python . , id() :

  • id()
  • , id(), , , ,

. , print id({}); print id({}) , .

+4

All Articles