Skip to the solution
HardDSA12 min read

What is a weak reference in Python?

729 views

The problem

Question presented to candidate: "What is a weak reference in Python, and how is it different from a normal reference? Give me a situation where you would use one, and tell me what the weakref module offers beyond weakref.ref."

What a strong answer should cover:

  • A weak reference refers to an object without increasing its reference count, so it does not keep the object alive; calling the ref returns the object, or None once it has been collected.
  • Use cases: caches that should not keep values alive (WeakValueDictionary), attaching data to objects you do not own (WeakKeyDictionary), observer/listener lists (WeakSet, WeakMethod), and back-pointers in trees that would otherwise create cycles.
  • Callbacks on weakref.ref, weakref.proxy (raises ReferenceError when dead), and weakref.finalize for cleanup.
  • Limits: int, str, tuple, list and dict instances cannot be weakly referenced (subclasses of list/dict can); classes with __slots__ need "__weakref__" in the slots.
  • The bound-method trap: weakref.ref(obj.method) dies immediately, which is why WeakMethod exists.

Code / implementation expected: Yes β€” a small WeakValueDictionary cache or a listener registry that cleans itself up.

  • weakref
  • memory

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythonref, callbacks, proxy, what can be weakly referenced, and WeakMethod
PythonA WeakValueDictionary cache, WeakKeyDictionary, WeakSet and a weak parent pointer

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 125 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextHard

How does CPython execute your code?

Continue