pythonstatic-methodspython-typing

How to add a type hint to a variable representing self in a static method within a class


I'm trying to add type hints to a static method in Python using typing.Self. However, the type hint isn't being applied to the self argument within the function itself.

from typing import Self

class Vect:
    x: float
    y: float

    @staticmethod
    def angle(v1: Self, v2: Self):
        return math.acos(v1 * v2 / v1.magnitude() / v2.magnitude())

The code is working but it doesn't give me any type hints in the angle method for variables v1 and v2.


Solution

  • typing.Self is meant to be used for instance methods returning self, or class methods that are alternative constructors, but static methods do not have a self or cls parameter.

    One way to type hint a static method is using forward references, that allows type hinting names not yet defined.

    Solution

    from typing import Self
    
    class Vect:
        x: float
        y: float
    
        @staticmethod
        def angle(v1: 'Vect', v2: 'Vect'):
            return math.acos(v1 * v2 / v1.magnitude() / v2.magnitude())