Skip to content

Commit 6a06e36

Browse files
committed
Allow self assignment
1 parent d211513 commit 6a06e36

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

mypy/checker.py

+11-3
Original file line numberDiff line numberDiff line change
@@ -2426,7 +2426,7 @@ def check_assignment(self, lvalue: Lvalue, rvalue: Expression, infer_lvalue_type
24262426

24272427
# Special case: only non-abstract non-protocol classes can be assigned to
24282428
# variables with explicit type Type[A], where A is protocol or abstract.
2429-
if not self.check_concrete_only_assign(lvalue_type, rvalue_type, rvalue):
2429+
if not self.check_concrete_only_assign(lvalue_type, lvalue, rvalue_type, rvalue):
24302430
return
24312431
if rvalue_type and infer_lvalue_type and not isinstance(lvalue_type, PartialType):
24322432
# Don't use type binder for definitions of special forms, like named tuples.
@@ -2444,8 +2444,16 @@ def check_assignment(self, lvalue: Lvalue, rvalue: Expression, infer_lvalue_type
24442444
self.infer_variable_type(inferred, lvalue, rvalue_type, rvalue)
24452445
self.check_assignment_to_slots(lvalue)
24462446

2447-
def check_concrete_only_assign(self, lvalue_type: Optional[Type],
2448-
rvalue_type: Type, rvalue: Expression) -> bool:
2447+
def check_concrete_only_assign(self,
2448+
lvalue_type: Optional[Type],
2449+
lvalue: Expression,
2450+
rvalue_type: Type,
2451+
rvalue: Expression) -> bool:
2452+
if (isinstance(lvalue, NameExpr) and isinstance(rvalue, NameExpr)
2453+
and lvalue.node == rvalue.node):
2454+
# This means that we reassign abstract class to itself. Like `A = A`
2455+
return True
2456+
24492457
rvalue_type = get_proper_type(rvalue_type)
24502458
lvalue_type = get_proper_type(lvalue_type)
24512459
if not (

test-data/unit/check-abstract.test

+5
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,11 @@ var = A1 # E: Can only assign concrete classes to a variable of type "Callable[[
277277
var = B1 # E: Can only assign concrete classes to a variable of type "Callable[[], A]"
278278
var = C1 # OK
279279

280+
# Self assign:
281+
A = A # OK
282+
B = B # OK
283+
C = C # OK
284+
280285
[case testInstantiationAbstractsInTypeForClassMethods]
281286
from typing import Type
282287
from abc import abstractmethod

test-data/unit/check-protocols.test

+5
Original file line numberDiff line numberDiff line change
@@ -1644,6 +1644,11 @@ var = P1 # E: Can only assign concrete classes to a variable of type "Callable[[
16441644
var = B1 # OK
16451645
var = C1 # OK
16461646

1647+
# Self assign:
1648+
P = P # OK
1649+
B = B # OK
1650+
C = C # OK
1651+
16471652
[case testInstantiationProtocolInTypeForClassMethods]
16481653
from typing import Type, Protocol
16491654

0 commit comments

Comments
 (0)