2. Use Self for fluent instance return types

Use Self when a method returns an instance of its own class.

Using Self keeps fluent APIs accurate across inheritance without repeating the concrete class name or falling back to loose return types. It becomes more valuable as these methods accumulate across a hierarchy.

Note

Python 3.11+

2.1. Don’t do this

1class Query:
2    def filter(self, expr: str) -> 'Query':
3        return self

2.2. Do this

1from typing import Self
2
3class Query:
4    def filter(self, expr: str) -> Self:
5        return self