Python Memory Management and Tips Transcripts
Chapter: Python variables and memory
Lecture: Concept: Flyweight design pattern

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Let's talk about a cool little optimization that Python uses for some of the objects that
0:06 are common and reused. Now you've heard me talk about the numbers, and seeing small numbers behave differently than others.
0:12 And that's because Python applies what's called the flyweight design pattern to them.
0:17 So let me just read what Wikipedia had to say about it: "in computer programming, flyweight is a software design pattern.
0:22 A flyweight is an object that minimizes memory usage by sharing as much data as possible with other similar objects". So,
0:29 for example, numbers that have the same value could literally be the same place in memory. Those are immutable. It is a way to use objects
0:37 in large numbers when a simple, repeated representation would use an unacceptable amount of memory.
0:43 So, like if you have the number 3 appear 1000 times like that's gonna be say, that would be 28k when really it could just be
0:51 28. So often some parts of the object state can be shared. It's a common practice to hold them in external data structures and pass them to objects
0:59 temporarily when they're used. Okay, so that's the flyweight design pattern, and you'll see that Python uses that some of the time,
1:06 especially around numbers.


Talk Python's Mastodon Michael Kennedy's Mastodon