Skip to content

Commit a412fc5

Browse files
authored
Improve readability of typing._ProtocolMeta.__instancecheck__ (#104649)
1 parent 9c5aa89 commit a412fc5

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

Lib/typing.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1801,9 +1801,11 @@ def __subclasscheck__(cls, other):
18011801
def __instancecheck__(cls, instance):
18021802
# We need this method for situations where attributes are
18031803
# assigned in __init__.
1804-
is_protocol_cls = getattr(cls, "_is_protocol", False)
1804+
if not getattr(cls, "_is_protocol", False):
1805+
# i.e., it's a concrete subclass of a protocol
1806+
return super().__instancecheck__(instance)
1807+
18051808
if (
1806-
is_protocol_cls and
18071809
not getattr(cls, '_is_runtime_protocol', False) and
18081810
not _allow_reckless_class_checks(depth=2)
18091811
):
@@ -1813,17 +1815,16 @@ def __instancecheck__(cls, instance):
18131815
if super().__instancecheck__(instance):
18141816
return True
18151817

1816-
if is_protocol_cls:
1817-
getattr_static = _lazy_load_getattr_static()
1818-
for attr in cls.__protocol_attrs__:
1819-
try:
1820-
val = getattr_static(instance, attr)
1821-
except AttributeError:
1822-
break
1823-
if val is None and callable(getattr(cls, attr, None)):
1824-
break
1825-
else:
1826-
return True
1818+
getattr_static = _lazy_load_getattr_static()
1819+
for attr in cls.__protocol_attrs__:
1820+
try:
1821+
val = getattr_static(instance, attr)
1822+
except AttributeError:
1823+
break
1824+
if val is None and callable(getattr(cls, attr, None)):
1825+
break
1826+
else:
1827+
return True
18271828

18281829
return False
18291830

0 commit comments

Comments
 (0)