Skip to content
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

gh-74690: typing: Simplify and optimise _ProtocolMeta.__instancecheck__ #103159

Merged
Merged
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
14 changes: 3 additions & 11 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2024,20 +2024,12 @@ def __instancecheck__(cls, instance):
raise TypeError("Instance and class checks can only be used with"
" @runtime_checkable protocols")

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)
):
if super().__instancecheck__(instance):
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:
Expand All @@ -2047,7 +2039,7 @@ def __instancecheck__(cls, instance):
else:
return True

return super().__instancecheck__(instance)
return False


class Protocol(Generic, metaclass=_ProtocolMeta):
Expand Down