Optional[TypeVar] does not preserve type of TypeVar when given Union type
Open
Nobody has claimed this yet.
bug
topic-join-v-union
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
When passing a union into an Optional[TypeVar], we expect to preserve the type of the TypeVar.
To Reproduce
from typing import Optional, TypeVar, TypedDict, Union
T = TypeVar("T")
def non_null(var: Optional[T]) -> T:
assert var is not None
return var
def test(a_union: Union[str, int]) -> None:
value: Union[str, int] = non_null(a_union)
Expected Behavior
Success: no issues found in 1 source file
Actual Behavior
test.py:16: error: Incompatible types in assignment (expression has type "object", variable has type "Union[str, int])" [assignment]
Your Environment
- Mypy version used: 1.8.0
- Python version used: 3.9
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
No repository file or test is named; begin with the supplied Python reproducer and run mypy against it to confirm the reported object-versus-Union error. Trace the Optional[TypeVar] handling for a Union argument, and consider the work complete when the example reports no issues as expected.
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