Sobes.tech
Junior — Middle

How is object lifetime management handled in Python and what stages does its lifecycle include?

sobes.tech AI

Answer from AI

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

The lifecycle of an object includes the following stages:

  1. Creation — the object is created in memory, and space is allocated.
  2. Usage — the object is accessible through references (variables).
  3. Reference counting — when a reference is created or assigned, the counter increases; when a reference is deleted, it decreases.
  4. Deletion — when the reference count of an object reaches zero, the memory is freed.
  5. Garbage collection — for objects involved in cyclic references, a separate garbage collection mechanism periodically searches for and deletes such objects.

Example:

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

obj = MyClass()  # Creating an object
ref = obj       # Increasing reference count

del obj         # Decreasing reference count

del ref         # Reference count becomes 0, object is deleted

Thus, the lifetime of an object in Python is managed automatically, which simplifies memory management.