Skip to content

How do I type hint a method with the type of the enclosing class?

In Python, you can use the self keyword to refer to the instance of the enclosing class within a method. To type hint self with the type of the enclosing class, use Self from the typing module (Python 3.11+) or typing_extensions. Here's an example:

Type hint a method with the type of the enclosing class in Python

python
from typing import Self

class MyClass:
    def my_method(self: Self) -> None:
        pass

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

This will type hint the my_method method to accept an instance of MyClass as its first argument, and return None. If you intended to type hint a class method instead, use @classmethod with cls: Self or cls: Type[MyClass].

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.