Python Self Type for Method Return Annotations
Learn how to use Python's Self type to annotate methods that return the instance, with correct type inference in subclasses and fluent interfaces.

When a method returns the instance it was called on, annotating its return type correctly becomes more subtle than it looks. The Self type, added in Python 3.11, solves a long-standing problem: how to tell the type checker that the return type is exactly the class of the instance, not just the base class. This article explains what Python's Self type is, how to use it, and why it matters for inheritance and fluent APIs.
The Problem with Returning Self
Consider a simple builder class:
class Builder:
def __init__(self):
self.value = 0
def add(self, amount: int) -> "Builder":
self.value += amount
return selfThe string annotation "Builder" works at runtime, but it creates a subtle issue. If you subclass Builder and call add() on the subclass, the type checker infers the return type as Builder, not the subclass. This forces unnecessary casts or breaks chained calls that rely on subclass-specific methods.
class SpecialBuilder(Builder):
def extra(self) -> "SpecialBuilder":
return self
# Even though the runtime value is a SpecialBuilder, add() is inferred to return Builder
SpecialBuilder().add(1).extra() # Error: 'Builder' has no attribute 'extra'The root cause is that the annotation is fixed to the class where it is written, not to the actual runtime type of self.
Introducing the Self Type
Python 3.11 added Self to the typing module. It represents the type of the current instance, including subclasses. Here is the same builder using Self:
from typing import Self
class Builder:
def __init__(self):
self.value = 0
def add(self, amount: int) -> Self:
self.value += amount
return selfNow when add() is called on a SpecialBuilder, the return type is inferred as SpecialBuilder, not Builder. This makes chained calls work without casts.
Why Self Beats Using the Class Name
Using the class name directly, even with from __future__ import annotations, does not adapt to inheritance. Self is a special form that the type checker resolves to the type of self at the call site. It is equivalent to writing a TypeVar bound to the class, but it is more concise and easier to read.
For example, the following explicit TypeVar approach is functionally similar:
from typing import TypeVar
T = TypeVar("T", bound="Builder")
class Builder:
def add(self: T, amount: int) -> T:
self.value += amount
return selfBut Self is cleaner and avoids the extra variable. It also works with classmethods that return an instance of the class, which is harder to express cleanly with a TypeVar.
Self with Inheritance and Fluent Interfaces
Self shines in fluent interfaces where methods return self to allow chaining. When you subclass a fluent class, Self ensures that all inherited methods return the subclass type, preserving the chain.
class Query:
def filter(self, condition: str) -> Self:
# apply filter
return self
def sort(self, key: str) -> Self:
# apply sort
return self
class UserQuery(Query):
def with_role(self, role: str) -> Self:
# add role filter
return self
# All methods return UserQuery, so chaining works
UserQuery().filter("active").sort("name").with_role("admin")Without Self, this chain would break at with_role() because filter() and sort() would return Query.
Alternatives: TypeVar and String Annotations
Before Python 3.11, developers used two main approaches:
- String annotations with the class name. This is simple but breaks inheritance, as shown earlier.
- TypeVar bound to the class. This works but requires an extra variable and is less readable.
Here is a comparison:
| Approach | Syntax | Inheritance Support | Readability |
|---|---|---|---|
| String annotation | -> "Builder" | No | Moderate |
| TypeVar bound | -> T with T = TypeVar("T", bound="Builder") | Yes | Lower |
| Self | -> Self | Yes | High |
Use Self when you need to return the exact instance type. Use a TypeVar when you need to relate the return type to a specific argument type, such as def merge(self, other: T) -> T. For returning self, string annotations are best treated as a fallback for older Python versions without Self.
Common Pitfalls and Edge Cases
Self is not a magic bullet. It represents the type of self, so it should only be used when a method actually returns self or a new instance of the same class. If a method returns a different type, Self is incorrect.
Another edge case appears with generic classes. Self also works when the class is generic. For example:
from typing import Generic, Self, TypeVar
T = TypeVar("T")
class Container(Generic[T]):
def set(self, value: T) -> Self:
self.value = value
return selfHere, Self retains Container[int] when called on an instance of Container[int]. This is more precise than annotating the return as the unparameterized Container.
One limitation is that Self is not a general-purpose type alias. It is meant for annotations that refer to the current instance or class, not for arbitrary class-scope declarations. Attempting to use it in a base class list or as a class-body variable annotation will not give you the current instance type.
Compatibility and Migration
Self is available in Python 3.11 and later. For older versions, you can use from __future__ import annotations to postpone annotation evaluation, but that does not provide Self. You would need to use a TypeVar or the typing_extensions backport:
from typing_extensions import Self # for Python < 3.11typing_extensions is the standard way to use Self on older Python versions. It provides the same semantics and is widely used in libraries that must support multiple Python releases.
When migrating existing code, start by replacing string annotations that return self with Self. Then run a type checker like mypy or pyright to verify that subclass behavior is correct. This change is purely in annotations and does not affect runtime behavior, so it is safe to adopt incrementally.
For projects that already use TypeVar for this purpose, switching to Self reduces boilerplate and improves readability, but it is not required. The main benefit of Self is consistency across methods and clearer intent for future maintainers.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.