python / typing

Python static typing home. Hosts the documentation and a user help forum.
https://typing.readthedocs.io/
Other
1.6k stars 235 forks source link

[spec] Overload processing order #1803

Open srittau opened 3 months ago

srittau commented 3 months ago

It's my understanding that overloads are processed in order. I.e. given the following overloads:

@overload
def foo(x: int) -> None: ...
@overload
def foo(x: int | str) -> None: ...
@overload
def foo(x: str) -> None: ...

When called with an int, the first overload is matched, when called with a str, the second is matched. The third is never matched. (Not going into what happens when called with int | str.) Currently, this behavior is not mentioned in the spec.

srittau commented 3 months ago

Also, overload "merging" behavior plays into this a little. E.g. given the example above and assuming that only the first and last overload were specified, could foo be called with int | str. I think the answer is "no". The call must match one of the overloads exactly and only that signature is looked at. But I'm not sure whether there aren't type checkers that are smarter.

JelleZijlstra commented 3 months ago

Overloads are generally virtually unspecified, and the behavior of different type checkers doesn't match that well. I know this is on Eric's list of potential areas to cover, but it will be hard to specify the behavior precisely as there is a lot of complexity.