What is the type hint for a method?

Question:

What is the right type hint for a method? There is typing.Callable, but I’m looking for a method type hint, and typing.Callable[[Self, ...], ...] is not working.

I’ve tried this but it doesn’t work:

class _Object:
    """An empty object for method type."""

    def method(self) -> None:
        """
        A method.

        :return None: Nothing.
        """
        return None


MethodType: Type = type(_Object().method)

MethodType is a type and not a type alias. Which type should I use then? I’m using Python 3.11.

Asked By: Virinas-code

||

Answers:

types.MethodType would be the annotation to use for "specifically a method object", but most of the time, typing.Callable will be more useful.

Answered By: user2357112

Callable applies to anything that is callable (functions, methods, classes, …).

from typing import Callable, TypeAlias  # TypeAlias available thru typing-extensions for Python <= 3.9


class MyBase:

    def method(self, i: int, j: int) -> int:
        return i + j


MethodType: TypeAlias = Callable[[MyBase, int, int], int]
a: MethodType = MyBase.method  # if you want to use a TypeAlias

b: Callable[[MyBase, int, int], int] = MyBase.method  # self must provided explicitly

my_base = MyBase()
c: Callable[[int, int], int] = my_base.method  # self is provided implicitly

As an extension of this, if you want to type methods generically i.e. for the methods of subclasses of a base class, you can use a TypeVar:

from typing import TypeVar

T = TypeVar("T", bound=MyBase)  # T is either an instance of MyBase or a subclass of MyBase


class MyDerived(MyBase):
    ...


def my_decorator(my_function: Callable[[MyBase, int, int], int]) -> Callable[[MyBase, int, int], int]:
    return my_function


def my_generic_decorator(my_function: Callable[[T, int, int], int]) -> Callable[[T, int, int], int]:
    return my_function


my_decorator(MyDerived.method)  # Parameter 1: type "MyBase" cannot be assigned to type "MyDerived"
my_generic_decorator(MyDerived.method)  # OK
Answered By: ringo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.