Skip to the solution
MediumDSA10 min read

What does typing.Self do and why does it beat TypeVar for methods?

119 views

The problem

Question presented to candidate: "I have a Shape class with chainable setters like set_scale() that return self, and a Circle subclass. If I annotate the setters -> Shape, chaining into a Circle-only method fails type checking. How does typing.Self fix that, and what did people do before it existed?"

What a strong answer should cover:

  • Self (PEP 673, Python 3.11, typing_extensions for older versions) means the type of the instance the method is called on, so Circle().set_scale(2) is a Circle
  • Annotating -> "Shape" loses the subclass; the pre-3.11 fix was a TypeVar bound to the class with self: T (and cls: type[T] for classmethods)
  • Self is equivalent to that bound TypeVar but needs no extra TypeVar, no annotated self, and works on attributes (next: Self | None), classmethods, __enter__ and Protocols
  • Returning Self obliges you to return self, cls(...) or type(self)(...): return Shape() is a type error, and runtime confirms it would give the wrong class
  • Limits: not allowed in static methods or module-level functions; Self in a parameter means "the same subclass", which is stricter than the base class

Code / implementation expected: Optional β€” a small fluent builder or alternative constructor, showing the -> Self annotation and the subclass coming back.

  • typing
  • self
  • python3.11

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

10 min read Β· 12 sections

Run the code

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

PythonFluent setters and a classmethod constructor that keep the subclass
PythonThe hard-coded-class bug, the old TypeVar spelling, Self in attributes and __enter__

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 110 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

How do closures capture variables in Python?

Continue