Skip to content

Commit 9075541

Browse files
committed
Cache the cached property *results* in a global var
1 parent dd7a45f commit 9075541

2 files changed

Lines changed: 6 additions & 18 deletions

File tree

src/attr/_make.py

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -496,7 +496,7 @@ def _transform_attrs(
496496
return _Attributes(AttrsClass(attrs), base_attrs, base_attr_map)
497497

498498

499-
_cached_property_descriptors = {}
499+
_cached_property_results = {}
500500

501501

502502
def _make_cached_property_uncached(original_cached_property_func, cls):
@@ -547,26 +547,16 @@ def _make_cached_property_uncached(original_cached_property_func, cls):
547547
defline,
548548
*doc_lines,
549549
" cls = self.__class__",
550-
f" descriptor = cached_property_descriptors.get((cls, '{name}'))",
551-
" if descriptor is None:",
552-
" for entry in type.__dict__['__mro__'].__get__(cls):",
553-
f" descriptor = entry.__dict__.get('{name}_cache')",
554-
" if descriptor is not None:",
555-
f" cached_property_descriptors[cls, '{name}'] = descriptor",
556-
" break",
557-
" try:",
558-
" return descriptor.__get__(self, cls)",
559-
" except AttributeError:",
560-
" pass",
561-
" result = original_cached_property(self)",
562-
" descriptor.__set__(self, result)",
550+
f" result = cached_property_results.get((cls, '{name}', id(self)), NOTHING)",
551+
" if result is NOTHING:",
552+
f" result = cached_property_results[cls, '{name}', id(self)] = original_cached_property(self)",
563553
" return result",
564554
]
565555
unique_filename = _generate_unique_filename(
566556
cls, original_cached_property_func
567557
)
568558
glob = {"original_cached_property": original_cached_property_func,
569-
"cached_property_descriptors": _cached_property_descriptors}
559+
"cached_property_results": _cached_property_results, "NOTHING": NOTHING}
570560
return _linecache_and_compile("\n".join(lines), unique_filename, glob)[
571561
name
572562
]
@@ -938,8 +928,6 @@ def _create_slots_class(self):
938928
if cached_properties:
939929
class_annotations = _get_annotations(self._cls)
940930
for name, func in cached_properties.items():
941-
# Add cached properties to names for slotting.
942-
names += (name + "_cache",)
943931
# Clear out function from class to avoid clashing.
944932
del cd[name]
945933
additional_closure_functions_to_update.append(func)

tests/test_slots.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -848,7 +848,7 @@ class A:
848848
def f(self):
849849
return self.x
850850

851-
assert set(A.__slots__) == {"x", "f_cache", "__weakref__"}
851+
assert set(A.__slots__) == {"x", "__weakref__"}
852852
assert "__dict__" not in dir(A)
853853

854854

0 commit comments

Comments
 (0)