Skip to the solution
MediumDSA6 min read

How does a + b dispatch in Python?

826 views

The problem

Question presented to candidate: "When Python evaluates a + b, what actually happens? Which object's method gets called, what happens if it does not know how to add the other type, and how is a += b different?"

What a strong answer should cover:

  • a + b calls type(a).__add__(a, b); if that is missing or returns NotImplemented, Python calls type(b).__radd__(b, a); if that also fails, TypeError: unsupported operand type(s) for +.
  • NotImplemented is a special value to return (not NotImplementedError to raise), meaning "I cannot handle this type, ask the other side".
  • The subclass rule: if type(b) is a subclass of type(a) and overrides __radd__, b.__radd__ is tried first; if both operands have the same type, __radd__ is never tried.
  • Methods are looked up on the type, not the instance, so patching obj.__add__ has no effect on obj + x.
  • a += b tries __iadd__ first (in-place, e.g. list mutates and aliases see it), falling back to a = a + b (e.g. tuple, int, str); the t[0] += [x] tuple gotcha.
  • CPython detail: since 3.11 all binary operators compile to a single BINARY_OP instruction with the operator in its argument.

Code / implementation expected: Optional β€” a small class with __add__ and __radd__ returning NotImplemented for unsupported types.

  • operators
  • data-model

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

6 min read Β· 10 sections

Run the code

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

PythonTracing __add__, __radd__, NotImplemented and the subclass rule
Python+= and __iadd__, the tuple gotcha and the BINARY_OP bytecode

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 64 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 nextMedium

What are lambda functions and map/filter/reduce?

Continue