Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e9d1360

Browse files
gh-112345: typing.Protocol: Let failed subclasscheck show non-method members (#112344)
Co-authored-by: Alex Waygood <[email protected]>
1 parent d9fc152 commit e9d1360

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

Lib/test/test_typing.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4091,6 +4091,22 @@ def method(self) -> None: ...
40914091
self.assertIsInstance(Foo(), ProtocolWithMixedMembers)
40924092
self.assertNotIsInstance(42, ProtocolWithMixedMembers)
40934093

4094+
def test_protocol_issubclass_error_message(self):
4095+
class Vec2D(Protocol):
4096+
x: float
4097+
y: float
4098+
4099+
def square_norm(self) -> float:
4100+
return self.x ** 2 + self.y ** 2
4101+
4102+
self.assertEqual(Vec2D.__protocol_attrs__, {'x', 'y', 'square_norm'})
4103+
expected_error_message = (
4104+
"Protocols with non-method members don't support issubclass()."
4105+
" Non-method members: 'x', 'y'."
4106+
)
4107+
with self.assertRaisesRegex(TypeError, re.escape(expected_error_message)):
4108+
issubclass(int, Vec2D)
4109+
40944110

40954111
class GenericTests(BaseTestCase):
40964112

Lib/typing.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1828,8 +1828,13 @@ def __subclasscheck__(cls, other):
18281828
not cls.__callable_proto_members_only__
18291829
and cls.__dict__.get("__subclasshook__") is _proto_hook
18301830
):
1831+
non_method_attrs = sorted(
1832+
attr for attr in cls.__protocol_attrs__
1833+
if not callable(getattr(cls, attr, None))
1834+
)
18311835
raise TypeError(
1832-
"Protocols with non-method members don't support issubclass()"
1836+
"Protocols with non-method members don't support issubclass()."
1837+
f" Non-method members: {str(non_method_attrs)[1:-1]}."
18331838
)
18341839
if not getattr(cls, '_is_runtime_protocol', False):
18351840
raise TypeError(
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Improve error message when trying to call :func:`issubclass` against a
2+
:class:`typing.Protocol` that has non-method members.
3+
Patch by Randolf Scholz.

0 commit comments

Comments
 (0)