Python 3, an Illustrated Tour Transcripts
Chapter: Classes and inheritance
Lecture: Dictionary Key Sharing

Login or purchase this course to watch this video and the rest of the course contents.
0:01 In this video, I want to introduce an optimization that was brought to pass in pep 412 Python 3.3. This is called key sharing dictionaries
0:11 and it's a nice little optimization that will save memory when you're using Python 3. From the pep we read: key sharing allows dictionaries,
0:19 which are used as attribute dictionaries or the __dict__ attribute of an object
0:25 to share keys with other attribute dictionaries of instances of the same class. So let's just understand what that means.
0:32 Basically whenever you create a class in Python underneath the class there will be a __dict__ attribute
0:40 which will store the attribute names and map them to the values there. What happens is if you're creating a bunch instances of classes
0:47 that have a bunch of attributes, these attributes are typically strings and those strings will be repeated and so Python the interpreter
0:54 would go out and create a new string for each attribute and those strings could add up if you're creating thousands or many more instances of a class.
1:05 So this is a nice little optimization, what it does is it caches essentially the keys in a dictionary.
1:12 We also read from the pep that as a result of this optimization
1:15 these dictionaries are typically half the size of the current dictionary implementation. Benchmarking shows that memory use is reduced
1:22 by 10 to 20 percent for object-oriented programs with no significant change in memory use for other programs.
1:29 So you don't have to do anything about this you get to take advantage of this automatically.
1:33 Also note that this optimization does not apply to dictionaries only to the __dict__ dictionary in an instance.

Talk Python's Mastodon Michael Kennedy's Mastodon