mirror of https://github.com/python/cpython
Improve readability of `typing._ProtocolMeta.__instancecheck__` (#104649)
This commit is contained in:
parent
9c5aa8967b
commit
a412fc58cc
|
@ -1801,9 +1801,11 @@ class _ProtocolMeta(ABCMeta):
|
||||||
def __instancecheck__(cls, instance):
|
def __instancecheck__(cls, instance):
|
||||||
# We need this method for situations where attributes are
|
# We need this method for situations where attributes are
|
||||||
# assigned in __init__.
|
# 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 (
|
if (
|
||||||
is_protocol_cls and
|
|
||||||
not getattr(cls, '_is_runtime_protocol', False) and
|
not getattr(cls, '_is_runtime_protocol', False) and
|
||||||
not _allow_reckless_class_checks(depth=2)
|
not _allow_reckless_class_checks(depth=2)
|
||||||
):
|
):
|
||||||
|
@ -1813,17 +1815,16 @@ class _ProtocolMeta(ABCMeta):
|
||||||
if super().__instancecheck__(instance):
|
if super().__instancecheck__(instance):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
if is_protocol_cls:
|
getattr_static = _lazy_load_getattr_static()
|
||||||
getattr_static = _lazy_load_getattr_static()
|
for attr in cls.__protocol_attrs__:
|
||||||
for attr in cls.__protocol_attrs__:
|
try:
|
||||||
try:
|
val = getattr_static(instance, attr)
|
||||||
val = getattr_static(instance, attr)
|
except AttributeError:
|
||||||
except AttributeError:
|
break
|
||||||
break
|
if val is None and callable(getattr(cls, attr, None)):
|
||||||
if val is None and callable(getattr(cls, attr, None)):
|
break
|
||||||
break
|
else:
|
||||||
else:
|
return True
|
||||||
return True
|
|
||||||
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue