From e3cf5fa9246c4b38cd5342ad6d60dd359d1e8cb6 Mon Sep 17 00:00:00 2001 From: Pieter Eendebak Date: Tue, 5 May 2026 20:51:01 +0200 Subject: [PATCH 1/2] inspect: fast path _shadowed_dict for type --- Lib/inspect.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Lib/inspect.py b/Lib/inspect.py index d3af61b26e280a..344933ce4b1b9f 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -1740,6 +1740,9 @@ def _shadowed_dict(klass): # destroyed, and the dynamically created classes happen to be the only # objects that hold strong references to other objects that take up a # significant amount of memory. + # Fast path: `type` is the dominant caller; result is always _sentinel. + if klass is type: + return _sentinel return _shadowed_dict_from_weakref_mro_tuple( *[make_weakref(entry) for entry in _static_getmro(klass)] ) From dbd9fcf4970db7acde5368b0ac7c4adadc73ef38 Mon Sep 17 00:00:00 2001 From: Pieter Eendebak Date: Tue, 5 May 2026 21:18:30 +0200 Subject: [PATCH 2/2] inspect: cache last metaclass in _check_class MRO loop Consecutive MRO entries usually share their metaclass, so call _shadowed_dict at most once per distinct metaclass. --- Lib/inspect.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Lib/inspect.py b/Lib/inspect.py index 344933ce4b1b9f..b2d105cffa20ec 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -1706,9 +1706,13 @@ def _check_instance(obj, attr): def _check_class(klass, attr): + last_meta = None for entry in _static_getmro(klass): - if _shadowed_dict(type(entry)) is _sentinel and attr in entry.__dict__: - return entry.__dict__[attr] + meta = type(entry) + if meta is last_meta or _shadowed_dict(meta) is _sentinel: + last_meta = meta + if attr in entry.__dict__: + return entry.__dict__[attr] return _sentinel