3 ms·
Ask HN: Is Python's dict key-sharing exclusive to class instance variables?
Modern Python versions (3.6+) have a memory performance optimization for dictionaries, where dict keys are shared between various class instances.
I am asking if plain Python's dictionaries have the same optimization?
Given the two dicts with shared keys:
d1 = {"name": "Havoc", "hand": "left"}
d2 = {"name": "Malice", "hand": "right"}
Are "name" and "hand" shared between these two or does each one have a separate key inside Python's memory pool?
EDIT:
No, the keys of normal dictionaries are not shared. As outlined in the PEP 412, only internal dictionaries of class instances share their keys:
https://www.python.org/dev/peps/pep-0412/
Good for OOP in Python, I guess.
- yokaze 5y agoNot sure if your example is considered to be complete, but AFAIK, static strings with the same content are the same instance. I'm side stepping your question in a way, but you can validate that easily with the "is" keyword. for k1,k2 in itertools.zip_longest(d1, d2): print(k1 is k2)
- wheelerof4te 5y agoYou make a good point, but I believe that the behaviour you see is more because of cPython's internal string handling. At least that is what PEP 412 is implying. For example: s1 = "cookie" s2 = "cookie" print(s1 is s2) # should print True