Python Memory Management and Tips Transcripts
Chapter: Course conclusion and review
Lecture: Garbage collection
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Previously, I said Python uses reference counting for almost all of the things, but it does not use it for all of the things
0:08
because sometimes reference counting fundamentally is broken and just cannot be used. And we talked about where that was.
0:15
That's cycles. Even if it's not just one thing refers to another, which refers back, but a very long,
0:21
complicated chain of links. If any of those form a cycle, they'll never have their reference count go to zero, so that will never get collected.
0:31
That memory would be leaked. So there's a generational garbage collector that lives in Python
0:36
that goes around and looks for things that are in these cycles. It only tracks container objects, classes,
0:43
dictionaries and so on, and it has three generations. generation zero, one, and two. Zero, by default, runs when the number of new objects minus
0:53
the deletions recently, whenever it checked last, exceeds 700. It's going to do a Gen zero collection,
0:59
and then one of the 10 times it's gonna do a gen one and zero, and then finally, one out of 100 times,
1:05
it'll do Gen two, one, and zero, and check all the memory that's hanging around. So
1:10
Python has this combination of both reference counting with a backup garbage collector to catch the
1:16
places where reference counting breaks, that's cycles.