pythonoverloadingpython-typing

How to define overloaded type signatures?


I have a Python function with an overloaded signature, for example float → float, str → int. I would like it to have it typed correctly, using annotations etc., so that mypy can check it correctly, and that tools like autocomplete will work. Is this possible? I appreciate different tools will have varying support, so mypy can be the standard for this question. I can use any released version of Python 3.


Solution

  • Yes, you can use the @typing.overload decorator.

    From https://docs.python.org/3/library/typing.html#typing.overload:

    @overload
    def process(response: None) -> None:
        ...
    @overload
    def process(response: int) -> tuple[int, str]:
        ...
    @overload
    def process(response: bytes) -> str:
        ...
    def process(response):
        <actual implementation>
    

    Those ellipses (...) are literal. You will actually type three dots for each overloaded function signature. The actual code will go in the final definition.