[Python-checkins] Improve readability of `typing._ProtocolMeta.__instancecheck__` (#104649)
AlexWaygood
webhook-mailer at python.org
Fri May 19 09:30:10 EDT 2023
https://github.com/python/cpython/commit/a412fc58ccb8c6739b179137321cbbb1abebcd2f
commit: a412fc58ccb8c6739b179137321cbbb1abebcd2f
branch: main
author: Alex Waygood <Alex.Waygood at Gmail.com>
committer: AlexWaygood <Alex.Waygood at Gmail.com>
date: 2023-05-19T14:30:02+01:00
summary:
Improve readability of `typing._ProtocolMeta.__instancecheck__` (#104649)
files:
M Lib/typing.py
diff --git a/Lib/typing.py b/Lib/typing.py
index b60eb94351f9..96393d6a0281 100644
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -1801,9 +1801,11 @@ def __subclasscheck__(cls, other):
def __instancecheck__(cls, instance):
# We need this method for situations where attributes are
# assigned in __init__.
- is_protocol_cls = getattr(cls, "_is_protocol", False)
+ if not getattr(cls, "_is_protocol", False):
+ # i.e., it's a concrete subclass of a protocol
+ return super().__instancecheck__(instance)
+
if (
- is_protocol_cls and
not getattr(cls, '_is_runtime_protocol', False) and
not _allow_reckless_class_checks(depth=2)
):
@@ -1813,17 +1815,16 @@ def __instancecheck__(cls, instance):
if super().__instancecheck__(instance):
return True
- if is_protocol_cls:
- getattr_static = _lazy_load_getattr_static()
- for attr in cls.__protocol_attrs__:
- try:
- val = getattr_static(instance, attr)
- except AttributeError:
- break
- if val is None and callable(getattr(cls, attr, None)):
- break
- else:
- return True
+ getattr_static = _lazy_load_getattr_static()
+ for attr in cls.__protocol_attrs__:
+ try:
+ val = getattr_static(instance, attr)
+ except AttributeError:
+ break
+ if val is None and callable(getattr(cls, attr, None)):
+ break
+ else:
+ return True
return False
More information about the Python-checkins
mailing list