Skip to content

Commit 0fa3184

Browse files
authored
Enhance type resolution for instance variables
Added logic to resolve types for instance variables and handle partial types.
1 parent fb16e93 commit 0fa3184

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

mypy/checker.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3313,6 +3313,33 @@ def check_assignment(
33133313
rvalue_type, lvalue_type, infer_lvalue_type = self.check_member_assignment(
33143314
lvalue, instance_type, lvalue_type, rvalue, context=rvalue
33153315
)
3316+
## --PATCH-- (ISSUE №19996 --INTERNAL ERROR with allow_redefinition_new and undeclared instance variables)
3317+
proper_rvalue_type = get_proper_type(rvalue_type)
3318+
resolved_type = None
3319+
3320+
def can_resolve_partial(lvalue_type, proper_rvalue_type):
3321+
return lvalue_type.type is None and not isinstance(proper_rvalue_type, NoneType)
3322+
3323+
def set_node_type(lvalue, typ):
3324+
if getattr(lvalue, "node", None) and hasattr(lvalue.node, "type"):
3325+
lvalue.node.type = typ
3326+
3327+
if isinstance(lvalue_type, PartialType) and can_resolve_partial(lvalue_type, proper_rvalue_type):
3328+
resolved_type = make_simplified_union([proper_rvalue_type, NoneType()])
3329+
elif lvalue_type.type is not None and isinstance(proper_rvalue_type, Instance):
3330+
if rvalue_type.type == lvalue_type.type:
3331+
resolved_type = rvalue_type
3332+
3333+
if resolved_type is not None:
3334+
lvalue_type = resolved_type
3335+
set_node_type(lvalue, resolved_type)
3336+
else:
3337+
self.fail(
3338+
f"Cannot resolve type for instance variable '{lvalue.name}', please annotate",
3339+
lvalue,
3340+
)
3341+
return
3342+
33163343
else:
33173344
# Hacky special case for assigning a literal None
33183345
# to a variable defined in a previous if

0 commit comments

Comments
 (0)