Do you think garbage collector can track all the Python objects?

Python uses two techniques to clean up garbage. One is reference counting, which affects all objects but which can't clean up objects that directly or indirectly refer to each other. That's where the actual garbage collector comes in: python has the gc module, which searches for cyclic references in objects it knows about. Only objects that can potentially be part of a reference cycle participate in the cyclic gc. So, for example, lists do, but strings do not; strings don't reference any other objects.

All Python classes and their instances automatically get tracked by the cyclic gc. Types defined in C aren't, unless they put in a little effort. All the builtin types that could be part of a cycle do. But this does mean the gc module only knows about the types that play along.

Apart from the collection mechanism there's also the fact that Python has its own aggregating memory allocator (obmalloc), which allocates entire memory arenas and uses the memory for most of the smaller objects it creates. Python now does free these areas when they're completely empty (for a long time it didn't), but actually emptying an area is fairly rare: because Python objects aren't movable, you can't just move some stragglers to another area.

Updated on: 30-Jul-2019


Kickstart Your Career

Get certified by completing the course

Get Started