Incorrect type narrowing when unpacking union of tuple on an existing variable
Open
Nobody has claimed this yet.
bug
priority-0-high
topic-type-narrowing
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
When unpacking a tuple with Union types over existing variables, some of the types disappear.
To Reproduce
import random
def foo() -> tuple[int, None] | tuple[int, str]:
if random.choice((True, False)):
return 0, None
return 5, "thing"
res = None
status, res = foo()
reveal_type(res) # builtins.str
Expected Behavior
res should be an Optional[str], not a str.
Actual Behavior
The Optional gets lost in the assignment.
Your Environment
- Mypy version used: 0.950
- Mypy command-line flags:
- Mypy configuration options from
mypy.ini(and other config files): - Python version used: 3.10
- Operating system and version: Manjaro Linux x86_64 5.15.41-1-MANJARO
This may be related to #9731, but I'm not sure about it.
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
The issue names no repository file or test; start by running the provided reproducer with mypy 0.950 on Python 3.10 and review related issue #9731. Trace tuple-unpacking assignment and type narrowing, with completion shown when reveal_type(res) reports Optional[str] rather than str.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers, devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 45/100