Skip to content

Commit

Permalink
pythongh-74690: Optimise isinstance() checks for nominal subclasses…
Browse files Browse the repository at this point in the history
… of runtime-checkable protocols
  • Loading branch information
AlexWaygood committed Mar 30, 2023
1 parent ecc5441 commit 694960d
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 1 deletion.
4 changes: 3 additions & 1 deletion Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1998,6 +1998,8 @@ class _ProtocolMeta(ABCMeta):
# This metaclass is really unfortunate and exists only because of
# the lack of __instancehook__.
def __instancecheck__(cls, instance):
if super().__instancecheck__(instance):
return True
# We need this method for situations where attributes are
# assigned in __init__.
if (
Expand All @@ -2019,7 +2021,7 @@ def __instancecheck__(cls, instance):
getattr(instance, attr) is not None)
for attr in _get_protocol_attrs(cls)):
return True
return super().__instancecheck__(instance)
return False


class Protocol(Generic, metaclass=_ProtocolMeta):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Speed up :func:`isinstance` checks against :func:`runtime-checkable
protocols <typing.runtime_checkable>` by 20x for nominal subclasses of the
protocol. Patch by Alex Waygood.

0 comments on commit 694960d

Please sign in to comment.