Mypy don't narrow types of 2 variables based on its combination
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Mypy don't narrow types of 2 variables based on its combination.
x: Literal["a", "b"] = a_or_b()
y: Literal["a", "b"] = a_or_b()
if not (x == "a" and y == "a") and x == "a":
# At this point, the type of y should be Literal["b"],
# but mypy reports "Union[Literal['a'], Literal['b']]"
reveal_type(y)
Note: the above if block can be separated into 2, which is probably more likely scenario in real codebase, such that:
if x == "a" and y == "a":
# some code...
pass
elif x == "a":
# At this point, the type of y should be Literal["b"],
# but mypy reports "Union[Literal['a'], Literal['b']]"
reveal_type(y)
To Reproduce
https://mypy-play.net/?mypy=latest&python=3.12&gist=9d0b24fba42e824b220e087003559068
Expected Behavior
Mypy narrows the type of y to be Literal["b"]
Actual Behavior
Mypy doesn't narrow the type and reports the type of y to be "Union[Literal['a'], Literal['b']]"
Your Environment
- Mypy version used: 1.7.1
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.12.0
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 linked mypy-play reproducer using Mypy 1.7.1 and Python 3.12, then compare the two conditional forms and their reveal_type output. Done means the second branch narrows y from Literal["a", "b"] to Literal["b"] without regressing the existing behavior.
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
- 35/100