Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 739
user83455 Avatar asked Oct 26 '25 09:10

user83455


1 Answers

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.

like image 193
JM0 Avatar answered Oct 27 '25 22:10

JM0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!