Skip to content

Commit

Permalink
Fix for issue #10514 and #17118
Browse files Browse the repository at this point in the history
Fixes type narrowing for negative integer literals
  • Loading branch information
gilesgc committed May 16, 2024
1 parent cdc956b commit aaeb04b
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 aaeb04b

Please sign in to comment.