Skip to content

Commit a2c1657

Browse files
authored
gh-149436: Speed up inspect.getattr_static for the common-metaclass case (#149437)
Consecutive MRO entries usually share their metaclass, so call _shadowed_dict at most once per distinct metaclass.
1 parent cc5cf14 commit a2c1657

2 files changed

Lines changed: 10 additions & 2 deletions

File tree

Lib/inspect.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1709,9 +1709,13 @@ def _check_instance(obj, attr):
17091709

17101710

17111711
def _check_class(klass, attr):
1712+
last_meta = None
17121713
for entry in _static_getmro(klass):
1713-
if _shadowed_dict(type(entry)) is _sentinel and attr in entry.__dict__:
1714-
return entry.__dict__[attr]
1714+
meta = type(entry)
1715+
if meta is last_meta or _shadowed_dict(meta) is _sentinel:
1716+
last_meta = meta
1717+
if attr in entry.__dict__:
1718+
return entry.__dict__[attr]
17151719
return _sentinel
17161720

17171721

@@ -1743,6 +1747,9 @@ def _shadowed_dict(klass):
17431747
# destroyed, and the dynamically created classes happen to be the only
17441748
# objects that hold strong references to other objects that take up a
17451749
# significant amount of memory.
1750+
# Fast path: `type` is the dominant caller; result is always _sentinel.
1751+
if klass is type:
1752+
return _sentinel
17461753
return _shadowed_dict_from_weakref_mro_tuple(
17471754
*[make_weakref(entry) for entry in _static_getmro(klass)]
17481755
)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve performance of :meth:`inspect.getattr_static`.

0 commit comments

Comments
 (0)