Skip to content

Commit 182eba9

Browse files
committed
Handle another edge case
1 parent 0649efe commit 182eba9

3 files changed

Lines changed: 25 additions & 2 deletions

File tree

mypy/binder.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,10 @@ def update_from_options(self, frames: list[Frame]) -> bool:
318318
# variable types to be widened using subsequent assignments. This is
319319
# tricky to support for instance attributes (primarily due to deferrals),
320320
# so we don't use it for them.
321-
old_semantics = not self.bind_all or extract_var_from_literal_hash(key) is None
321+
var = extract_var_from_literal_hash(key)
322+
old_semantics = (
323+
not self.bind_all or var is None or not var.is_inferred and not var.is_argument
324+
)
322325
if old_semantics and any(x is None for x in resulting_values):
323326
# We didn't know anything about key before
324327
# (current_value must be None), and we still don't

mypy/checker.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3427,6 +3427,9 @@ def check_assignment(
34273427
self.options.allow_redefinition_new
34283428
and lvalue_type is not None
34293429
and not isinstance(lvalue_type, PartialType)
3430+
and isinstance(lvalue, NameExpr)
3431+
and isinstance(lvalue.node, Var)
3432+
and lvalue.node.is_inferred
34303433
):
34313434
# TODO: Can we use put() here?
34323435
self.binder.assign_type(lvalue, lvalue_type, lvalue_type)

test-data/unit/check-redefine2.test

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def f1() -> None:
6969
x: Union[int, str] = 0
7070
reveal_type(x) # N: Revealed type is "builtins.int | builtins.str"
7171
x = ""
72-
reveal_type(x) # N: Revealed type is "builtins.str"
72+
reveal_type(x) # N: Revealed type is "builtins.int | builtins.str"
7373

7474
[case testNewRedefineUninitializedCodePath3]
7575
# flags: --allow-redefinition-new --local-partial-types
@@ -1378,3 +1378,20 @@ async def test(x: Optional[str]) -> None:
13781378
if x is None:
13791379
x = await gen("foo")
13801380
reveal_type(x) # N: Revealed type is "builtins.str"
1381+
1382+
[case testNewRedefineNarrowingOnFirstAssignment]
1383+
# flags: --allow-redefinition-new --local-partial-types
1384+
from typing import Any
1385+
1386+
li: list[int]
1387+
1388+
def test() -> None:
1389+
x: list[Any] = li
1390+
reveal_type(x) # N: Revealed type is "builtins.list[Any]"
1391+
1392+
if bool():
1393+
y: list[Any] = li
1394+
else:
1395+
y = li
1396+
reveal_type(y) # N: Revealed type is "builtins.list[Any]"
1397+
[builtins fixtures/primitives.pyi]

0 commit comments

Comments
 (0)