python / mypy

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

generics fail to infer with an empty list #11393

Open DetachHead opened 3 years ago

DetachHead commented 3 years ago
from typing import TypeVar

T = TypeVar("T")

def default(value: T | None, value_if_none: T) -> T:
    return value_if_none if value is None else value

foo: list[str] | None = []

bar = default(foo, [])

# expected: list[str]
# actual: Revealed type is "builtins.object*"
reveal_type(bar) 

https://mypy-play.net/?mypy=latest&python=3.10&flags=strict%2Ccheck-untyped-defs%2Cdisallow-any-decorated%2Cdisallow-any-expr%2Cdisallow-any-explicit%2Cdisallow-any-generics%2Cdisallow-any-unimported%2Cdisallow-incomplete-defs%2Cdisallow-subclassing-any%2Cdisallow-untyped-calls%2Cdisallow-untyped-decorators%2Cdisallow-untyped-defs%2Cno-strict-optional%2Cwarn-incomplete-stub%2Cwarn-redundant-casts%2Cwarn-return-any%2Cwarn-unreachable%2Cwarn-unused-configs%2Cwarn-unused-ignores&gist=67ab7f5ec1dfea275e0d318ffadc1b18

KotlinIsland commented 3 years ago
def func(a: T, b: T) -> T:
    return a

reveal_type([1], [])  # object
reveal_type([1], cast(list[int], []))  # list[int]

I think mypy if failing to inject the type parameter of the first list into the partial type(list[<nothing>]) of the second list.