Sometimes, we want to type hint a method with the type of the enclosing class with Python.
In this article, we’ll look at how to type hint a method with the type of the enclosing class with Python.
How to type hint a method with the type of the enclosing class with Python?
To type hint a method with the type of the enclosing class with Python, we can import the annotations
module.
For instance, we write
from __future__ import annotations
class Position:
def __add__(self, other: Position) -> Position:
#...
to import the annotations
module with
from __future__ import annotations
Then we can add type hints for arguments and return types.
We set other
to have type Position
by putting it after the colon.
And we set the return type of add
to be Position
by putting after the ->
.
Conclusion
To type hint a method with the type of the enclosing class with Python, we can import the annotations
module.