Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b74829e

Browse files
authored
Fix for type narrowing of negative integer literals (#17256)
Fixes #10514 Fixes #17118 Negative integer literals were not being correctly handled in the type narrowing process, causing mypy errors such as "Statement is unreachable" despite the checked code being valid. This fix ensures that negative integer literals are properly considered in if-statements.
1 parent cdc956b commit b74829e

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

mypy/plugins/default.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -489,7 +489,7 @@ def int_neg_callback(ctx: MethodContext, multiplier: int = -1) -> Type:
489489
return ctx.type.copy_modified(
490490
last_known_value=LiteralType(
491491
value=multiplier * value,
492-
fallback=ctx.type,
492+
fallback=fallback,
493493
line=ctx.type.line,
494494
column=ctx.type.column,
495495
)

test-data/unit/check-narrowing.test

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2089,3 +2089,28 @@ if isinstance(x, (Z, NoneType)): # E: Subclass of "X" and "Z" cannot exist: "Z"
20892089
reveal_type(x) # E: Statement is unreachable
20902090

20912091
[builtins fixtures/isinstance.pyi]
2092+
2093+
[case testTypeNarrowingReachableNegative]
2094+
# flags: --warn-unreachable
2095+
from typing import Literal
2096+
2097+
x: Literal[-1]
2098+
2099+
if x == -1:
2100+
assert True
2101+
2102+
[typing fixtures/typing-medium.pyi]
2103+
[builtins fixtures/ops.pyi]
2104+
2105+
[case testTypeNarrowingReachableNegativeUnion]
2106+
from typing import Literal
2107+
2108+
x: Literal[-1, 1]
2109+
2110+
if x == -1:
2111+
reveal_type(x) # N: Revealed type is "Literal[-1]"
2112+
else:
2113+
reveal_type(x) # N: Revealed type is "Literal[1]"
2114+
2115+
[typing fixtures/typing-medium.pyi]
2116+
[builtins fixtures/ops.pyi]

0 commit comments

Comments
 (0)