[issue42127] functools.cached_property possibly disables key-sharing instance dictionaries

Raymond Hettinger report at bugs.python.org
Fri Oct 23 17:41:48 EDT 2020


Raymond Hettinger <raymond.hettinger at gmail.com> added the comment:

> Essentially it means that types using cached_property are less
> likely to enjoy the benefits of shared keys.

I don't think anything can be done about it.  @cached_property and key-sharing dicts are intrinsically at odds with one another.  Likewise, @cached_property doesn't work with classes that define __slots__.

FWIW, there is an alternative that works with both key-sharing dicts and __slots__.  You can stack property() on top of functools.cache():

    class A:
        def __init__(self, x):
                self.x = x

        @property
        @cache
        def square(self):
                print('Called!')
                return self.x ** 2

            
    >>> a = A(10)
    >>> a.square
    Called!
    100
    >>> b = A(11)
    >>> b.square
    Called
    121
    >>> a.square
    100
    >>> b.square
    121

----------
nosy: +rhettinger

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42127>
_______________________________________


More information about the Python-bugs-list mailing list