Self type in Python

Redowan Delowar February 28, 2022
Source

PEP-673 introduces the Self type and it's coming to Python 3.11. However, you can already use that now via the typing_extensions module.

The Self type makes annotating methods that return the instances of the corresponding classes trivial. Before this, you'd have to do some mental gymnastics to statically type situations as follows:

The class Animal has a from_description class method that acts as an additional constructor. It takes a description string, and then builds and returns an instance of the same class. The return type of the method is annotated as Animal here. However, doing this makes the child class Dog conflate its identity with the Animal class. If you execute the snippet, it won't raise any runtime error. Also, Mypy will complain about the type:

To fix this, we'll have to make sure that the return type of the from_description class method doesn't confuse the type checker. This is one way to do this:

In the above snippet, first I had to declare a TypeVar and bind that to the Animal class. Then I had to explicitly type the cls variable in the from_description method. This time, the type checker will be happy. While this isn't a lot of work, it surely goes against the community convention. Usually, we don't explicitly type the self, cls variables and instead, let the type checker figure out their types. Also, subjectively, this sticks out like a sore thumb.

PEP-673 allows us to solve the issue elegantly:

If you run Mypy against the second snippet, it won't complain.

Typing instance methods that return self

Take a look at this:

The increment and decrement method of the Counter class return the instance of the same class after performing the operations on the start value. This is a perfect case where the Self type can be useful.

Typing new methods

You can also type the new method easily:

The new method in the Config class validates the var before constructing an instance of the class. The Self type makes it easy to annotate the method.

Further reading

Discussion in the ATmosphere

Loading comments...