Skip to content

Commit 361a3ea

Browse files
authored
gh-74690: Micro-optimise typing._get_protocol_attrs (#103152)
Improve performance of `isinstance()` checks against runtime-checkable protocols
1 parent 2a4d8c0 commit 361a3ea

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

Lib/typing.py

+12-8
Original file line numberDiff line numberDiff line change
@@ -1903,15 +1903,19 @@ class _TypingEllipsis:
19031903
"""Internal placeholder for ... (ellipsis)."""
19041904

19051905

1906-
_TYPING_INTERNALS = ['__parameters__', '__orig_bases__', '__orig_class__',
1907-
'_is_protocol', '_is_runtime_protocol']
1906+
_TYPING_INTERNALS = frozenset({
1907+
'__parameters__', '__orig_bases__', '__orig_class__',
1908+
'_is_protocol', '_is_runtime_protocol'
1909+
})
19081910

1909-
_SPECIAL_NAMES = ['__abstractmethods__', '__annotations__', '__dict__', '__doc__',
1910-
'__init__', '__module__', '__new__', '__slots__',
1911-
'__subclasshook__', '__weakref__', '__class_getitem__']
1911+
_SPECIAL_NAMES = frozenset({
1912+
'__abstractmethods__', '__annotations__', '__dict__', '__doc__',
1913+
'__init__', '__module__', '__new__', '__slots__',
1914+
'__subclasshook__', '__weakref__', '__class_getitem__'
1915+
})
19121916

19131917
# These special attributes will be not collected as protocol members.
1914-
EXCLUDED_ATTRIBUTES = _TYPING_INTERNALS + _SPECIAL_NAMES + ['_MutableMapping__marker']
1918+
EXCLUDED_ATTRIBUTES = _TYPING_INTERNALS | _SPECIAL_NAMES | {'_MutableMapping__marker'}
19151919

19161920

19171921
def _get_protocol_attrs(cls):
@@ -1922,10 +1926,10 @@ def _get_protocol_attrs(cls):
19221926
"""
19231927
attrs = set()
19241928
for base in cls.__mro__[:-1]: # without object
1925-
if base.__name__ in ('Protocol', 'Generic'):
1929+
if base.__name__ in {'Protocol', 'Generic'}:
19261930
continue
19271931
annotations = getattr(base, '__annotations__', {})
1928-
for attr in list(base.__dict__.keys()) + list(annotations.keys()):
1932+
for attr in (*base.__dict__, *annotations):
19291933
if not attr.startswith('_abc_') and attr not in EXCLUDED_ATTRIBUTES:
19301934
attrs.add(attr)
19311935
return attrs

0 commit comments

Comments
 (0)