FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

gh-74690: `typing._ProtocolMeta.__instancecheck__`: Exit early for protocols that only have callable members by AlexWaygood · Pull Request #103310 · python/cpython · GitHub

/ cpython Public
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (2) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
14 changes: 14 additions & 0 deletions Lib/test/test_typing.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
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 Lib/typing.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
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

Back | FazBrowse Home | New Git URL