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,
0:05 but it does not use it for all of the things
0:07 because sometimes reference counting fundamentally is broken and just cannot be used.
0:13 And we talked about where that was.
0:14 That's cycles. Even if it's not just one thing refers to another,
0:18 which refers back, but a very long,
0:20 complicated chain of links. If any of those form a cycle,
0:24 they'll never have their reference count go to zero,
0:28 so that will never get collected.
0:30 That memory would be leaked. So there's a generational garbage collector that lives in Python
0:35 that goes around and looks for things that are in these cycles.
0:39 It only tracks container objects, classes,
0:42 dictionaries and so on, and it has three generations.
0:46 generation zero, one, and two. Zero, by default, runs when the number of new objects minus
0:52 the deletions recently, whenever it checked last, exceeds 700.
0:56 It's going to do a Gen zero collection,
0:58 and then one of the 10 times it's gonna do a gen one and zero,
1:02 and then finally, one out of 100 times,
1:04 it'll do Gen two, one, and zero, and check all the memory that's hanging around. So
1:09 Python has this combination of both reference counting with a backup garbage collector to catch the
1:15 places where reference counting breaks, that's cycles.