Skip to content

Commit

Permalink
Fix for type narrowing of negative integer literals (#17256)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
gilesgc committed May 17, 2024
1 parent cdc956b commit b74829e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion mypy/plugins/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,7 @@ def int_neg_callback(ctx: MethodContext, multiplier: int = -1) -> Type:
return ctx.type.copy_modified(
last_known_value=LiteralType(
value=multiplier * value,
fallback=ctx.type,
fallback=fallback,
line=ctx.type.line,
column=ctx.type.column,
)
Expand Down
25 changes: 25 additions & 0 deletions test-data/unit/check-narrowing.test
Original file line number Diff line number Diff line change
Expand Up @@ -2089,3 +2089,28 @@ if isinstance(x, (Z, NoneType)): # E: Subclass of "X" and "Z" cannot exist: "Z"
reveal_type(x) # E: Statement is unreachable

[builtins fixtures/isinstance.pyi]

[case testTypeNarrowingReachableNegative]
# flags: --warn-unreachable
from typing import Literal

x: Literal[-1]

if x == -1:
assert True

[typing fixtures/typing-medium.pyi]
[builtins fixtures/ops.pyi]

[case testTypeNarrowingReachableNegativeUnion]
from typing import Literal

x: Literal[-1, 1]

if x == -1:
reveal_type(x) # N: Revealed type is "Literal[-1]"
else:
reveal_type(x) # N: Revealed type is "Literal[1]"

[typing fixtures/typing-medium.pyi]
[builtins fixtures/ops.pyi]

0 comments on commit b74829e

Please sign in to comment.