Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

gh-74690: typing._ProtocolMeta.__instancecheck__: Exit early for protocols that only have callable members #103310

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
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
gh-74690: typing._ProtocolMeta.__instancecheck__: Exit early for prot…
…ocols that only have callable members
  • Loading branch information
AlexWaygood committed Apr 6, 2023
commit 8cc20e60e14e1d5f634e20b692a0064776bd232a
14 changes: 14 additions & 0 deletions 14 Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2577,6 +2577,18 @@ def meth(x): ...
class PG(Protocol[T]):
def meth(x): ...

@runtime_checkable
class WeirdProto(Protocol):
meth = str.maketrans

class CustomCallable:
def __call__(self, *args, **kwargs):
pass

@runtime_checkable
class WeirderProto(Protocol):
meth = CustomCallable()

class BadP(Protocol):
def meth(x): ...

Expand All @@ -2588,6 +2600,8 @@ def meth(x): ...

self.assertIsInstance(C(), P)
self.assertIsInstance(C(), PG)
self.assertIsInstance(C(), WeirdProto)
self.assertIsInstance(C(), WeirderProto)
with self.assertRaises(TypeError):
isinstance(C(), PG[T])
with self.assertRaises(TypeError):
Expand Down
6 changes: 5 additions & 1 deletion 6 Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2032,7 +2032,11 @@ def __instancecheck__(cls, instance):
if super().__instancecheck__(instance):
return True

if is_protocol_cls:
# Skip the below loop for protocols where `cls.__callable_proto_members_only__ == True`.
# For these protocols, this just duplicates checks that have already been done
# in the `_proto_hook` function,
# which is called as part of the super().__instancecheck__ method above.
if is_protocol_cls and not cls.__callable_proto_members_only__:
getattr_static = _lazy_load_getattr_static()
for attr in cls.__protocol_attrs__:
try:
Expand Down
Morty Proxy This is a proxified and sanitized view of the page, visit original site.