Sobes.tech
Junior — Middle

How is object deletion managed in Python and what is the sequence?

sobes.tech AI

Answer from AI

In Python, object deletion management is based on reference counting and a garbage collector for cyclic references.

The sequence of object deletion:

  1. Reference counting: Each object keeps track of the number of references to it. When this count reaches 0 — the object becomes unreachable.
  2. Memory release: If the reference count of an object is 0, the __del__ method is called (if defined), after which the memory for the object is freed.
  3. Garbage collector: For objects involved in cyclic references (when objects refer to each other), reference counting does not work. In such cases, Python runs a garbage collector that finds and removes cycles.

Example:

class MyClass:
    def __del__(self):
        print('Object deleted')

obj = MyClass()
del obj  # Decreases the reference count, if 0 — __del__ is called

Thus, deletion occurs automatically when the object becomes unreachable, first through reference counting, and then through the garbage collector for cycles.