Python Memory Management and Tips Transcripts
Chapter: Course conclusion and review
Lecture: Reference counting

Login or purchase this course to watch this video and the rest of the course contents.
0:00 The flip side of allocating memory is we're gonna have to clean it up.
0:02 So you saw the primary way for
0:05 the vast majority of objects in Python, that this is done, is through reference counting.
0:10 Everything in Python is a PyObject pointer and allocated on the heap is a PyObject.
0:15 And we pulled up just a tiny bit here of the code from "object.h".
0:20 The most important part around this is that there's this thing called "ob ref count" that
0:25 is like either 32 bit or 64 bit or whatever it happens to be here.
0:30 We've got this special type here that every single thing derives from and it basically just
0:36 has this place for how many variables refer to it.
0:40 And that works almost all the time.
0:42 We've got a couple of variables.
0:44 One of them goes away and the count goes down.
0:47 If that count ever reaches zero, immediately
0:50 that thing is deleted. And by deleted,
0:53 We don't mean necessarily the memory is given back to the operating system.
0:57 Remember, we have the blocks,
0:59 we have the pools, and we have the arenas.
1:01 What it means is the space in the block is now free to accept another object
1:06 of that size of its small.
1:08 If its large, it probably is immediately deleted and given back to the operating system.
1:12 Again, if you want to see this,