MyPy fails on Union[str, int] < Union[str, int] when underlying type is known
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Given the following script I'm receiving several unexpected errors:
test.py:22: error: Unsupported operand types for < ("str" and "int")
test.py:22: error: Unsupported operand types for < ("int" and "str")
test.py:22: note: Both left and right operands are unions
test.py:24: error: Unsupported operand types for < ("str" and "int")
test.py:24: error: Unsupported operand types for < ("int" and "str")
test.py:24: note: Both left and right operands are unions
Found 4 errors in 1 file (checked 1 source file)
Even though the if-block and assert statement just before the comparison operator usage on a and b clearly filters out the case of mismatching types. I've only added the assert statement in the hope of telling mypy that these variables have the same type, but no luck there.
from typing import Union
def semver_prerelease_compare(lhs: str, rhs: str) -> bool:
a: Union[str, int]
b: Union[str, int]
for a, b in zip(lhs.split("."), rhs.split(".")):
try:
a = int(a)
except ValueError:
pass
try:
b = int(b)
except ValueError:
pass
if isinstance(a, int) and not isinstance(b, int):
# Numeric identifiers sort before non-numeric ones
return True
if type(a) != type(b):
return False
if a < b:
return True
elif b < a:
return False
return len(lhs) < len(rhs)
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
Reproduce the reported diagnostics by running mypy on test.py, then trace how the type(a) != type(b) guard affects narrowing for the a < b and b < a comparisons. Done when the equivalent-type guard no longer produces the reported str/int errors and the behavior is covered by a regression test.
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
- Mostly clear
- Newbie friendliness
- 42/100