Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-118013: Use weakrefs for the cache key in inspect._shadowed_dict #118202

Merged
merged 9 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@
from keyword import iskeyword
from operator import attrgetter
from collections import namedtuple, OrderedDict
from weakref import ref as make_weakref

# Create constants for the compiler flags in Include/code.h
# We try to get them from dis to avoid duplication
Expand Down Expand Up @@ -1832,9 +1833,11 @@ def _check_class(klass, attr):
return entry.__dict__[attr]
return _sentinel


@functools.lru_cache()
def _shadowed_dict_from_mro_tuple(mro):
for entry in mro:
def _shadowed_dict_from_weakref_mro_tuple(*weakref_mro):
for weakref_entry in weakref_mro:
entry = weakref_entry()
AlexWaygood marked this conversation as resolved.
Show resolved Hide resolved
dunder_dict = _get_dunder_dict_of_class(entry)
if '__dict__' in dunder_dict:
class_dict = dunder_dict['__dict__']
Expand All @@ -1844,8 +1847,12 @@ def _shadowed_dict_from_mro_tuple(mro):
return class_dict
return _sentinel


def _shadowed_dict(klass):
return _shadowed_dict_from_mro_tuple(_static_getmro(klass))
return _shadowed_dict_from_weakref_mro_tuple(
*[make_weakref(entry) for entry in _static_getmro(klass)]
sobolevn marked this conversation as resolved.
Show resolved Hide resolved
)


def getattr_static(obj, attr, default=_sentinel):
"""Retrieve attributes without triggering dynamic lookup via the
Expand Down
1 change: 0 additions & 1 deletion Lib/test/libregrtest/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,6 @@ def clear_caches():
except KeyError:
pass
else:
inspect._shadowed_dict_from_mro_tuple.cache_clear()
inspect._filesbymodname.clear()
inspect.modulesbyfile.clear()

Expand Down
Loading