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. So you saw the primary way for
0:06
the vast majority of objects in Python, that this is done, is through reference counting.
0:11
Everything in Python is a PyObject pointer and allocated on the heap is a PyObject. And we pulled up just a tiny bit here of the code from "object.h".
0:21
The most important part around this is that there's this thing called "ob ref count" that
0:26
is like either 32 bit or 64 bit or whatever it happens to be here.
0:31
We've got this special type here that every single thing derives from and it basically just has this place for how many variables refer to it.
0:41
And that works almost all the time. We've got a couple of variables. One of them goes away and the count goes down.
0:48
If that count ever reaches zero, immediately that thing is deleted. And by deleted,
0:54
We don't mean necessarily the memory is given back to the operating system. Remember, we have the blocks, we have the pools, and we have the arenas.
1:02
What it means is the space in the block is now free to accept another object of that size of its small.
1:09
If its large, it probably is immediately deleted and given back to the operating system. Again, if you want to see this, bit.ly/cPythonobject.