Open
Description
Bug Report
I have a generic class and function, which return Union containing TypeVar as in generic. Mypy will give error [arg-type] if I pass function result in another function which gets a object. But if i save the result in a variable and then pass it in function, mypy won't show error. It's very counterintuitive
To Reproduce
from typing import *
T = TypeVar("T")
D = TypeVar("D")
class Key: ...
class FancyKey(Generic[T]): ...
def get(key: FancyKey[T], default: D) -> D | T:
...
return default
def foo(value: object) -> Any: ...
key = FancyKey[Key]()
foo(
get(key, default=None)
) # mypy: Argument 1 to "bar" of "Bar" has incompatible type "Foo[Lab]"; expected "Foo[object]" [arg-type]
treasure = get(key, default=None) # no error
foo(treasure) # no error
Actual Behavior
mypy: Argument 1 to "bar" of "Bar" has incompatible type "Foo[Lab]"; expected "Foo[object]" [arg-type]
If a return-type function won't be generic or function will return not a Union - no error will be received
If type of value
change to Any - no error will be received
Maybe this issue related with another
Your Environment
- Mypy version used: 1.11.1
- Mypy command-line flags: no flags
- Mypy configuration options from
mypy.ini
(and other config files): no config - Python version used: 3.12
Activity
brianschubert commentedon Nov 2, 2024
topic-type-contextType context / bidirectional inference
This has to do with whether the signature of
get
is (over)inferred from the type context (yieldingdef (key: FancyKey[object], default: object) -> object
) or from the arguments types (yieldingdef (key: FancyKey[Key], default: None) -> Key | None
). In the first case, passingFancyKey[Key]
becomes invalid, since you declaredFancyKey[T]
to be invariant.