Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

In overloads, why is the implementation return type allowed to be broader than the overload return types? #2131

bzoracler started this conversation in General
Discussion options

The following causes a runtime error without any type-checker warning:

from typing import overload
@overload
def f(arg: int, /) -> int: ...
@overload
def f(arg: str, /) -> str: ...
def f(arg: int | str, /) -> int | str | bytes:
 return b""
f(1) + 1

Looking at the typing specs on Implementation consistency,

... the return type of all overloads should be assignable to the return type of the implementation.

this doesn't seem quite right, because a broader return type in the implementation will almost always cause runtime issues in the calling context or above, while a narrower return type in the implementation (coupled with overload consistency checks in the signature) should never cause type errors in the calling context:

@overload
def f(arg: int, /) -> int: ...
# Pyright and Pyrefly complain of the following overload and implementation,
# but it seems perfectly type-safe.
@overload
def f(arg: int | str, /) -> int | str: ...
def f(arg: int | str, /) -> int:
 return 1
You must be logged in to vote

Replies: 1 comment

Comment options

I think you're right.

The check that all overload return types are assignable to the implementation return type is not really necessary for soundness, but it is a useful consistency check, since it's probably a mistake to annotate an overload as returning a type outside what the implementation can return.

I think ideally we would also add a check that the implementation return type be assignable to the union of the overload return types -- that check is actually needed for soundness.

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants

AltStyle によって変換されたページ (->オリジナル) /