Mypy fails to deduce generic type if it has been previously deduced as `<nothing>`
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Mypy fails to deduce generic type if it has been previously deduced as <nothing>
To Reproduce
Minimal example to reproduce
from typing import Callable, TypeVar, Generic
T = TypeVar("T")
class Foo(Generic[T]):
pass
def decorate(foo: Foo[T] | None) -> Callable[[T], T]:
raise NotImplementedError
# Case 1
reveal_type(decorate(None)(str())) # Revealed type is "<nothing>"; Argument 1 has incompatible type "str"; expected <nothing>
# Case 2
reveal_type(decorate(Foo())(str())) # Revealed type is "<nothing>"; Argument 1 has incompatible type "str"; expected <nothing>
# Case 3
reveal_type(decorate(Foo[str]())(str())) # Revealed type is "builtins.str"
Playground link
Expected Behavior
I'am expecting mypy to work in case 1 and case 2 like in the following example, where generic variable T isn't constrainted
by upper function decorate and her arguments.
def decorate() -> Callable[[T], T]:
raise NotImplementedError
reveal_type(decorate()(str())) # Revealed type is "str"
This intuition comes from the fact, that in some cases generic variables is not deductible at some point, but later they are defined through context of usage, like in the following example:
l = [] # it's is like `list[<nothing>]` right now
l.append(int())
reveal_type(l) # Revealed type is `builtins.list[builtins.int]`
Actual Behavior
Mypy rejects case 1 and case 2 from the main example, but it's look counter-intuitive, therefore it looks like a bug
Your Environment
All examples were run on mypy-play.net using Python 3.10 and mypy == 0.971 without additional options
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the minimal examples in the issue and run them in mypy-play.net using Python 3.10 and mypy 0.971. Investigate why T remains <nothing> in cases 1 and 2; done means those cases infer str like case 3 and the no-argument example without rejecting the call.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 42/100