Sobes.tech
Junior — Middle

How to distinguish between weak and strong references in Python and what are their differences?

sobes.tech AI

Answer from AI

In Python, strong references are regular references to objects that increase the reference count of the object and prevent the garbage collector from deleting the object as long as at least one strong reference exists.

Weak references are references that do not increase the reference count of the object. They allow referencing the object but do not prevent its deletion by the garbage collector if no strong references remain.

The weakref module is used to work with weak references.

Example:

import weakref

class MyClass:
    pass

obj = MyClass()  # strong reference
weak_obj = weakref.ref(obj)  # weak reference

print(weak_obj())  # <__main__.MyClass object at ...>

del obj  # delete strong reference

print(weak_obj())  # None, object has been garbage collected

Differences:

  • A strong reference keeps the object in memory.
  • A weak reference allows tracking the object but does not prevent its deletion.
  • Weak references are useful for caching and preventing cyclic references that hinder garbage collection.