Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 41 additions & 10 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2426,16 +2426,7 @@ def check_assignment(self, lvalue: Lvalue, rvalue: Expression, infer_lvalue_type

# Special case: only non-abstract non-protocol classes can be assigned to
# variables with explicit type Type[A], where A is protocol or abstract.
rvalue_type = get_proper_type(rvalue_type)
lvalue_type = get_proper_type(lvalue_type)
if (isinstance(rvalue_type, CallableType) and rvalue_type.is_type_obj() and
(rvalue_type.type_object().is_abstract or
rvalue_type.type_object().is_protocol) and
isinstance(lvalue_type, TypeType) and
isinstance(lvalue_type.item, Instance) and
(lvalue_type.item.type.is_abstract or
lvalue_type.item.type.is_protocol)):
self.msg.concrete_only_assign(lvalue_type, rvalue)
if not self.check_concrete_only_assign(lvalue_type, lvalue, rvalue_type, rvalue):
return
if rvalue_type and infer_lvalue_type and not isinstance(lvalue_type, PartialType):
# Don't use type binder for definitions of special forms, like named tuples.
Expand All @@ -2453,6 +2444,46 @@ def check_assignment(self, lvalue: Lvalue, rvalue: Expression, infer_lvalue_type
self.infer_variable_type(inferred, lvalue, rvalue_type, rvalue)
self.check_assignment_to_slots(lvalue)

def check_concrete_only_assign(self,
lvalue_type: Optional[Type],
lvalue: Expression,
rvalue_type: Type,
rvalue: Expression) -> bool:
if (isinstance(lvalue, NameExpr) and isinstance(rvalue, NameExpr)
and lvalue.node == rvalue.node):
# This means that we reassign abstract class to itself. Like `A = A`
return True

rvalue_type = get_proper_type(rvalue_type)
lvalue_type = get_proper_type(lvalue_type)
if not (
isinstance(rvalue_type, CallableType) and
rvalue_type.is_type_obj() and
(rvalue_type.type_object().is_abstract or
rvalue_type.type_object().is_protocol)):
return True
Comment on lines +2459 to +2464
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Incomplete Type Check

The check only verifies rvalue_type properties but doesn't verify that lvalue_type is a callable type before proceeding to further checks. This could cause AttributeError if lvalue_type is None or a non-callable type, reducing reliability.

Standards
  • ISO-IEC-25010-Reliability-Fault-Tolerance
  • ISO-IEC-25010-Functional-Correctness-Appropriateness

Comment on lines +2459 to +2464
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Redundant Boolean Expressions

The boolean expression is structured as 'if not (condition)' followed by 'return True', which creates unnecessary cognitive load. Inverting the condition and returning False directly would improve readability and maintainability.

Standards
  • Clean-Code-Boolean-Logic
  • Maintainability-Quality-Readability


lvalue_is_a_type = (
isinstance(lvalue_type, TypeType) and
isinstance(lvalue_type.item, Instance) and
(lvalue_type.item.type.is_abstract or
lvalue_type.item.type.is_protocol)
)

lvalue_is_a_callable = False
if isinstance(lvalue_type, CallableType):
ret_type = get_proper_type(lvalue_type.ret_type)
lvalue_is_a_callable = (
isinstance(ret_type, Instance) and
(ret_type.type.is_abstract or ret_type.type.is_protocol)
)
Comment thread
visz11 marked this conversation as resolved.

if lvalue_is_a_type or lvalue_is_a_callable:
Comment on lines +2475 to +2481
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Callable Return Validation

The code only checks if the return type is an Instance, but misses other possible abstract or protocol types that could be wrapped in other type constructs. This creates a logical gap where abstract/protocol types in more complex return type structures won't trigger the warning.

Suggested change
ret_type = get_proper_type(lvalue_type.ret_type)
lvalue_is_a_callable = (
isinstance(ret_type, Instance) and
(ret_type.type.is_abstract or ret_type.type.is_protocol)
)
if lvalue_is_a_type or lvalue_is_a_callable:
lvalue_is_a_callable = False
if isinstance(lvalue_type, CallableType):
ret_type = get_proper_type(lvalue_type.ret_type)
if isinstance(ret_type, Instance):
lvalue_is_a_callable = (ret_type.type.is_abstract or ret_type.type.is_protocol)
elif isinstance(ret_type, TypeType) and isinstance(ret_type.item, Instance):
lvalue_is_a_callable = (ret_type.item.type.is_abstract or ret_type.item.type.is_protocol)
Standards
  • Algorithm-Correctness-Pattern-Matching
  • Logic-Verification-Type-Checking

# `lvalue_type` here is either `TypeType` or `CallableType`:
self.msg.concrete_only_assign(cast(Type, lvalue_type), rvalue)
return False
return True
Comment on lines +2481 to +2485
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Type Confusion Risk

Unchecked type cast could lead to runtime errors if lvalue_type is None. If None is passed to cast(), a TypeError would be raised, potentially causing denial of service.

Suggested change
if lvalue_is_a_type or lvalue_is_a_callable:
# `lvalue_type` here is either `TypeType` or `CallableType`:
self.msg.concrete_only_assign(cast(Type, lvalue_type), rvalue)
return False
return True
if lvalue_is_a_type or lvalue_is_a_callable:
# `lvalue_type` here is either `TypeType` or `CallableType`:
if lvalue_type is not None:
self.msg.concrete_only_assign(cast(Type, lvalue_type), rvalue)
return False
return True
Standards
  • CWE-476
  • CWE-704


# (type, operator) tuples for augmented assignments supported with partial types
partial_type_augmented_ops: Final = {
('builtins.list', '+'),
Expand Down
32 changes: 32 additions & 0 deletions test-data/unit/check-abstract.test
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,38 @@ if int():
var_old = C # OK
[out]

[case testInstantiationAbstractsWithCallables]
from typing import Callable, Type
from abc import abstractmethod

class A:
@abstractmethod
def m(self) -> None: pass
class B(A): pass
class C(B):
def m(self) -> None:
pass

var: Callable[[], A]
var() # OK

var = A # E: Can only assign concrete classes to a variable of type "Callable[[], A]"
var = B # E: Can only assign concrete classes to a variable of type "Callable[[], A]"
var = C # OK

# Type aliases:
A1 = A
B1 = B
C1 = C
var = A1 # E: Can only assign concrete classes to a variable of type "Callable[[], A]"
var = B1 # E: Can only assign concrete classes to a variable of type "Callable[[], A]"
var = C1 # OK

# Self assign:
A = A # OK
B = B # OK
C = C # OK

[case testInstantiationAbstractsInTypeForClassMethods]
from typing import Type
from abc import abstractmethod
Expand Down
30 changes: 30 additions & 0 deletions test-data/unit/check-protocols.test
Original file line number Diff line number Diff line change
Expand Up @@ -1619,6 +1619,36 @@ if int():
var_old = B # OK
var_old = C # OK

[case testInstantiationProtocolWithCallables]
from typing import Callable, Protocol

class P(Protocol):
def m(self) -> None: pass
class B(P): pass
class C:
def m(self) -> None:
pass

var: Callable[[], P]
var() # OK

var = P # E: Can only assign concrete classes to a variable of type "Callable[[], P]"
var = B # OK
var = C # OK

# Type aliases:
P1 = P
B1 = B
C1 = C
var = P1 # E: Can only assign concrete classes to a variable of type "Callable[[], P]"
var = B1 # OK
var = C1 # OK

# Self assign:
P = P # OK
B = B # OK
C = C # OK

[case testInstantiationProtocolInTypeForClassMethods]
from typing import Type, Protocol

Expand Down