Weird interaction between TypeVar and union
Open
Nobody has claimed this yet.
bug
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
See this code.
from typing import TypeVar
T = TypeVar("T", list, dict)
def ctor(cls: type[T]) -> T:
return cls()
def ctor_union(cls: type[list] | type[dict]) -> list | dict:
return cls()
def ctor_union_proxy(cls: type[list] | type[dict]) -> list | dict:
return ctor(cls)
produces
main.py:12: error: Value of type variable "T" of "ctor" cannot be "Collection[Any]" [type-var]
main.py:12: error: Incompatible return value type (got "Collection[Any]", expected "list[Any] | dict[Any, Any]") [return-value]
Found 2 errors in 1 file (checked 1 source file)
possibly duplicate of #9424.
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
Run the linked mypy-play example with Python 3.12 and mypy master, then inspect the calls to ctor and ctor_union_proxy in main.py. Compare the diagnostics for the direct union constructor with the proxy call and confirm the intended behavior before tracing the relevant type-variable handling. Done means the reported interaction is resolved and covered by a regression test.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100