This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com
Last weekend, we had a live session on the internals of memory management in CPython. Unfortunately, the recording of that session got corrupted, so I recorded a video on it.
CPython uses a combination of reference counting and a generational garbage collector (GC) to manage the memory of the Python programs. Reference counting is a fairly simple technique and I’ve written a very detailed article on it. So in this video, I give a basic overview of reference counting and its implementation, but the majority of the focus is on the garbage collector and its implementation.
The garbage collector in CPython is used for cleaning up memory of objects which have cyclic references and thus cannot be cleaned up reference counting.
The video covers the following topics:
* How CPython manages memory
* Reference counting & its implementation details in CPython at the interpreter level
* In what situations reference counting does not work?
* GC implementation details:
* What is a generational GC?
* How and when the GC is scheduled to run?
* What does the GC do in CPython?
* The cyclic reference detection algorithm in the CPython GC
* Changes in reference counting and GC implementation due to removal of the global interpreter lock (GIL)
Upcoming Article
Although, this video is very detailed and tells you everything you need to know about theGC in CPython, it does not go into the source code (I do show some important struct definitions).
I’ve a very detailed article coming up in a few days on the GC internals in CPython, which goes into all the gory implementation details and walks you through the code to show how everything happens. So watch out for that as well. Perhaps having watched this video will help you get a better perspective when reading that article.
Upcoming Live Session on Building a Basic Remote Profiler for Python
I also have another live session coming up on 26th May where we will actually apply our knowledge of the CPython runtime internals to learn how tools like remote profilers or debuggers work. This will be very technical and will have lots of stuff to learn. I’m very excited about. You can checkout the details in the below post.
Support Confessions of a Code Addict
If you enjoy reading my articles and find value in them, please consider supporting Confessions of a Code Addict by becoming a paid subscriber. It takes several days of work to produce every piece that I write and your support will help keep it going. Although, I try to keep most of my articles open, I offer the following additional perks to the paid supporters:
* Free access to the monthly live sessions
* Access to past recordings of all the live sessions
* Option to schedule a 30 minute meeting with me every month to discuss anything you wish
The monthly plan is at Indian Rupees (INR) 550 ($6) and annual plan is at INR 4999 ($60).
Alternative Ways to Support
Many people report that their transactions fail on Substack, so I also have a couple of alternate options.
You can support me on buymeacoffee.com. You can either buy me coffees or become a member and I will upgrade you to a paid subscription here for the equivalent period.
Alternatively, you can also support me through GitHub sponsorship:
Audio and video play straight from the show's own hosting. PodSubs stores and serves no media.
Transcript
From the show. Tap a time to play from there.
SPEAKER_00Hey everyone, this is Abhinav from Confessions of a Code Addict. Last weekend we had a live session on the internals of memory management in CPython. I usually upload the recording of the session afterwards and share it with all of you, but unfortunately that recording got corrupted and I could not upload it. So what I'm going to do is redo the session, but this time I'll just record it without any live audience and I'll share it with
SPEAKER_00all of you. So this is what we are going to discuss in this session. We are going to talk about memory management in CPython. Specifically, we are going to talk about how does CPython implement memory management and what are the internal implementation details. So it turns out CPython actually uses a combination of reference counting and garbage collection. So we are going to learn the internal implementation details of how both of these things work in CPython.
SPEAKER_00And towards the end, we'll also see and discuss some of the changes which have happened in reference counting and garbage collection as part of the GIL removal. That is the global interpreter lock removal work that is going on in CPython. So let's get started. So let's start by talking about reference counting. So what is reference counting? So, Python is an object oriented language and everything is an object in Python.
SPEAKER_00Now, when we create an object, what is really happening is the CPython runtime behind the scenes, it creates an object. and it gives us back a reference to that object. So when I say s is equal to hello world, so I'm creating a string hello world and assigning it to a variable s. What is really happening is the runtime creates this object somewhere in memory with the value hello world, the type string,
SPEAKER_00and it stores the reference count here. And it assigns that reference to s. So the variable S is essentially a reference to an actual object. now when we assign that same object to more variables what happens is the reference count of that object gets incremented so instead of creating a new copy of that object the runtime behind the scenes it simply updates the reference count of that object and assigns that to the new variable so for example here we can see s2 is
SPEAKER_00equal to s so now that string object has reference count of 2 because now there are two references s and s2 pointing to it so that What this means is whenever we assign an object to a new variable, the reference count of that object gets incremented. Similarly, when those variables to which that object was assigned go out of the scope, the reference count gets decremented automatically behind the scenes. And as soon as the reference count of that object reaches zero,
SPEAKER_00the runtime goes and reallocates the memory of that object. all this increment, incrementation and increment and decrement of the reference count happens as part of the code execution. So, when I say S2 is equal to S, so during the execution of this assignment operation, the reference count of the string object would have been incremented so there is no all of this is pretty immediate and if I for example say del s2 so as I am deleting s2 from the memory so
SPEAKER_00immediately the interpreter would go and decrement the reference count for that string object so all of this happens immediately there is no delay or lag between these reference count changes. And if you want to play around, the SysModule provides a function called getRefCount. And if you pass it any object, it will give you the reference count of that object. The only thing I would like to highlight here is that the reference count returned
SPEAKER_00by this function is one higher than the actual reference count that you would expect. And the reason is that while this function is executing, we are passing that object as a parameter to this function. and as a result that function itself is holding a reference to this object while the function is executing and this output is generated while that function was executing that is why the reference count is one higher than the expected reference
SPEAKER_00count but as soon as the function returns the reference count would have been decremented by the runtime so the actual reference count at this point when we see two here is actually one So reference counting is pretty simple to understand, no complexity involved and it is equally simple to implement as well. So let's briefly look at some of the implementation details of reference counting. So the first thing we have to understand is where are these reference counts stored in memory.
SPEAKER_00So the CPython runtime needs to maintain the reference count for each object that it's creating for our program. So it makes sense that the reference counts are stored with the object itself. One possibility is that every object definition includes a reference count field in it. But that means all the other runtime code such as a garbage collection,
SPEAKER_00the reference count manipulation, the interpreter, everything has to be aware of the individual object types and their definitions of what fields are contained in them and where is the reference count present in them. That makes things quite complicated. So as a generic solution, the way it is done in cPython is the memory layout of the objects is segregated into two parts. So I am showing here the memory layout of a couple of objects.
SPEAKER_00Python objects. The first one is a floating point object and the second is a complex object. So here in both these objects you can see that there are two regions. One is this blue region and the other is a pink region. So the blue region is called the object header and every object has this header. So every object that we create in our Python programs has this header at the beginning of its memory. And then we have the pink region which is the object's body. So this is where we type specific details.
SPEAKER_00So for example the floating point object has to store the float value. So it has a double field inside it. Similarly the complex object has to store the real and imaginary. So it has the real and imaginary fields there. But the object header structure is consistent. Every object has the same object header with the same structure. Obviously with different contents inside. Now this header has two fields. One is the reference count. So this is where the object's reference count is stored.
SPEAKER_00And the other is a pointer to an object of type, pi type object. So, PyTypeObject is a struct which contains all the type specific details about that object. So, this will contain things like the type name, how to and then a bunch of function pointers that the type has to implement and populate those function pointers in the PyTypeObject instance. So some of the examples are a function to hash that object,
SPEAKER_00a function to deallocate an object of that type, how to perform various binary operations on an object of that specific type and things like that. So, I have a very detailed video on the type system internals where I have discussed the role of pi type object and I have discussed all the fields inside it. So, you can check that out. So,
SPEAKER_00as far as this discussion is concerned the header contains this obref counts field which is where reference counts are stored. These are the actual C struct definitions for the float type and the complex type. You can see this is the object header. The first field is an instance of type PyObject called ob-base and this guy also has the same first field. The PyObject struct is the struct which represents the object header and this is its definition.
SPEAKER_00The first field you can see here is the reference point and the other is the type pointer. Now how are these reference counts manipulated? So CPython internally has a couple of functions for incrementing and decrementing reference count which are called from all over the interpreter wherever the reference count has to be manipulated. So, this is PyIncre, which is used for incrementing the reference count. You can see it takes the object as a parameter and it simply does the increment.
SPEAKER_00And there is a check. So, there are certain objects which are tagged as immortal within the C500 runtime. These objects are essentially immutable and as a result, their reference count should never really change. So, for such objects, this check is present so that runtime doesn't really try to modify their reference count. And similarly this is the pydecref function which is used for decrementing the reference count. Here things are bit interesting so you can see as soon as the reference count is
SPEAKER_00decremented they are also checking whether the reference count has reached zero and if it has reached zero they immediately call the deallocate function to deallocate the memory of that object. Now, so you can see this deallocation happens immediately as the objects reference point is reaching the value 0 and within this deallocation what really happens is all Not only the memory of this object will get deallocated,
SPEAKER_00but before that if this object contains any other objects, those objects reference count is also decremented. And if those objects reference count has reached zero, then their deallocation will also get triggered. So this is cascading. Let's also see how this reference counting comes into the picture while our Python code is executing.
SPEAKER_00So, this is here I have a very simple function which takes two parameters a and b and returns a result of their sum and below that I am showing the disassembly of that function. So, python has this dis module which you can use to generate or print the disassembly of the of any function or module. Which contains a piece of code. If you don't know, CPython is a compiled language and it compiles code for a stack based virtual machine.
SPEAKER_00And these are the instructions. These are some of the instructions that that virtual machine supports. And because it's a stack based virtual machine, so it uses a stack for storing and retrieving data for executing its instructions. So it pushes and pops data as required for executing the instructions that it needs to execute. So in this case,
SPEAKER_00for executing this A plus B return, A plus B line of code, it is generating these four instructions. So load fast, load fast binary open, return value. So the load fast instruction, is used to take a value from the locals table and push it on to the stack, so all the local objects whether they are local variables in that function or they are parameters to that function, they are passed to the interpreter in the form of a locals table,
SPEAKER_00the table is indexed by a number, so 0 1 2, so every local object is stored in the table at some index. So here for example you can see this load fast instruction is receiving an argument value 0 and the second one is receiving an argument value of 1. So 0 and 1 are the indexes at which these instructions are going to look up the local table and whatever object is stored at that table they are going to read it.
SPEAKER_00Okay so what the load fast instruction actually does is it will read the local table at this specific index whatever object is on that index it will push it on to the stack as the top value. So these two loadfast instructions, what they are doing is they are reading A and B from the locals table and pushing them onto the stack. So when these two instructions finish, A and B are the top two values on the stack. Now the binary of instruction is simple.
SPEAKER_00It pops the top two values from the stack and it executes whatever binary operation has been passed to it as an argument. Here the argument is zero, which maps to the plus operation. So these are the three instructions where the reference count of A and B is being manipulated. So let's see how that happens. So this is the interpreter code for handling the load fast instruction.
SPEAKER_00So this is actual code taken from the CPython interpreter. This part handles the load fast instruction. And you can see what it is doing is it is looking up the local stable at this specific index. And whatever object it receives,
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com In the last video, we learned about copy-on-write (CoW) and understood its mechanics by digging inside the mmap pathway in the...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com In the last video, we discussed demand paging. Now, let’s move towards an even more interesting topic: copy-on-write (CoW). Just...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com In the previous video in our virtual memory series, we discussed demand paging. But that was mostly theoretical, explaining how...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com Welcome back to the video series on virtual memory based on my article on the same topic. It is also available in ebook format on...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com This is a short aside in our virtual memory series. We have talked extensively about the size of a virtual address and the virtual...