Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Memory & performanceSeniorOccasionalPractical

What does the `weakref` module provide, and when should you reach for a weak reference instead of a normal one?

Answer

A weak reference lets you hold a pointer to an object without increasing its reference count, so the referenced object can still be garbage-collected as if that weak reference did not exist; accessing an expired weak reference gives `None` (or raises, for `weakref.proxy`) instead of a valid object. This is the right tool for caches, observer/listener registries, and parent-child back-references, where a normal reference would either create a reference cycle the collector has to clean up, or would keep an object alive artificially just because a cache or listener list still points to it.

Strong answer includes

  • weak references don't increase the reference count
  • accessing an expired weakref yields None instead of the object
  • used for caches, observer registries, and parent back-references

Practical example

Python example
self._parent = weakref.ref(parent)

in a child node lets the parent be freed normally when nothing else references it, instead of the child's back-reference keeping it alive forever.

#memory-management#weakref

Sources

gc — Garbage collector interfacePython Software Foundation · Generational garbage collection and cyclic-reference behaviorThe Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modules