Skip to content

Commit

Permalink
Fix crash when nested class appears in a protocol (#13489)
Browse files Browse the repository at this point in the history
Fixes #6393

This is unspecified behavior in terms of PEP 544, so we just try to 
do something meaningful (see test case). At least we should not crash.
  • Loading branch information
ilevkivskyi authored Aug 24, 2022
1 parent f83835c commit 61a9b92
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
5 changes: 5 additions & 0 deletions mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
is_named_instance,
)
from mypy.typestate import SubtypeKind, TypeState
from mypy.typevars import fill_typevars_with_any
from mypy.typevartuples import extract_unpack, split_with_instance

# Flags for detected protocol members
Expand Down Expand Up @@ -1060,6 +1061,10 @@ def find_member(
return getattr_type
if itype.type.fallback_to_any:
return AnyType(TypeOfAny.special_form)
if isinstance(v, TypeInfo):
# PEP 544 doesn't specify anything about such use cases. So we just try
# to do something meaningful (at least we should not crash).
return TypeType(fill_typevars_with_any(v))
return None


Expand Down
20 changes: 20 additions & 0 deletions test-data/unit/check-protocols.test
Original file line number Diff line number Diff line change
Expand Up @@ -3118,3 +3118,23 @@ class P(Protocol):

class A(P): ...
A() # E: Cannot instantiate abstract class "A" with abstract attribute "f"

[case testProtocolWithNestedClass]
from typing import TypeVar, Protocol

class Template(Protocol):
var: int
class Meta: ...

class B:
var: int
class Meta: ...
class C:
var: int
class Meta(Template.Meta): ...

def foo(t: Template) -> None: ...
foo(B()) # E: Argument 1 to "foo" has incompatible type "B"; expected "Template" \
# N: Following member(s) of "B" have conflicts: \
# N: Meta: expected "Type[__main__.Template.Meta]", got "Type[__main__.B.Meta]"
foo(C()) # OK

0 comments on commit 61a9b92

Please sign in to comment.