From 9acfef839db0211417a0a951cdc305bbaae6afc8 Mon Sep 17 00:00:00 2001 From: AlexWaygood Date: Fri, 31 Mar 2023 23:47:11 +0100 Subject: [PATCH 1/2] typing: Optimise nominal subtypes in `_ProtocolMeta.__instancecheck__` --- Lib/typing.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Lib/typing.py b/Lib/typing.py index a88542cfbaecd5..343cc98fa73292 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -2013,6 +2013,9 @@ def __instancecheck__(cls, instance): raise TypeError("Instance and class checks can only be used with" " @runtime_checkable protocols") + if super().__instancecheck__(instance): + return True + if not is_protocol_cls and issubclass(instance.__class__, cls): return True @@ -2031,7 +2034,8 @@ def __instancecheck__(cls, instance): getattr(instance, attr) is not None) for attr in protocol_attrs): return True - return super().__instancecheck__(instance) + + return False class Protocol(Generic, metaclass=_ProtocolMeta): From 99b19ae97305a8440c76873a7ed6a7ef6dcb0e8e Mon Sep 17 00:00:00 2001 From: AlexWaygood Date: Mon, 3 Apr 2023 17:44:17 +0100 Subject: [PATCH 2/2] Simplify and optimise --- Lib/typing.py | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/Lib/typing.py b/Lib/typing.py index ac9f554c95e2dc..f50e9b0a93b061 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -2027,20 +2027,9 @@ def __instancecheck__(cls, instance): if super().__instancecheck__(instance): return True - if not is_protocol_cls and issubclass(instance.__class__, cls): - return True - - protocol_attrs = _get_protocol_attrs(cls) - - if ( - _is_callable_members_only(cls, protocol_attrs) - and issubclass(instance.__class__, cls) - ): - return True - if is_protocol_cls: getattr_static = _lazy_load_getattr_static() - for attr in protocol_attrs: + for attr in _get_protocol_attrs(cls): try: val = getattr_static(instance, attr) except AttributeError: