Rodrigo Girão Serrão 🐍🚀 @mathspp.com · Jan 14

When a method returns the argument `self`, use `typing.Self` to annotate the return type of the method: ```py from typing import Self class P: def some_method(self) -> Self: ... return self ``` Why is this useful?

1 likes 1 replies

?

Replies

Rodrigo Girão Serrão 🐍🚀 · Jan 14

This is especially useful if `C` inherits from `P`: ```py class C(P): pass ``` The return type of `C.some_method` is inferred to be the subclass itself: ```py from typing import reveal_type reveal_type(C().some_method()) # C ``` But only because of `Self`!