python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.16k stars 2.77k forks source link

Mypy should ensure overloads are compatible with the implementation #11086

Open spagh-eddie opened 2 years ago

spagh-eddie commented 2 years ago

Bug Report

Mypy should ensure overloads are compatible with the implementation

To Reproduce

from typing import Union, overload
from typing_extensions import Literal

@overload
def f(*, flag: Literal[True]) -> float: ...
@overload
def f(*, flag: Literal[False] = False) -> str: ...
def f(*, flag: bool = False) -> Union[str, float]:
    return 5

reveal_type(f(flag=True))
reveal_type(f(flag=False))
reveal_type(f())

Expected Behavior

an error along the lines of "signature 2 incompatible with implementation" because it cannot return a str when flag=False

Actual Behavior

$ mypy test.py 
test.py:11:13: note: Revealed type is "builtins.float"
test.py:12:13: note: Revealed type is "builtins.str"
test.py:13:13: note: Revealed type is "builtins.str"

Your Environment

KotlinIsland commented 2 years ago

Here's a minified example

from typing import overload

@overload
def func(i: int) -> int: ...
@overload
def func(i: str) -> str: ...
def func(i: str | int) -> str | int:
    return "AMONGUS"  # SUS ALERT!