This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Epic_Wink
Recipients Epic_Wink, docs@python
Date 2019-10-21.23:53:20
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1571702000.84.0.0143851282892.issue38553@roundup.psfhosted.org>
In-reply-to
Content
As I discovered during working on bpo-38545, `functools.cached_property` natively supports cached value setting/updating and clearing (via attribute assignment and deletion, respectively) through mechanisms defined in the language for non-data descriptors:

    class A:
        j = 0
    
        @functools.cached_property
        def b(self):
            self.j += 1
            return self.j

    a = A()
    print(a.b)  # 1
    print(a.b)  # 1
    del a.b
    print(a.b)  # 2
    print(a.b)  # 2
    a.b = 42
    print(a.b)  # 42
    print(a.b)  # 42
    del a.b
    print(a.b)  # 3
    print(a.b)  # 3

I propose that this functionality be documented, for two reasons:
1. To notify developers that this functionality is available, and how to access it
2. To notify developers that this functionality needs to be explicitly disabled. This is important as the built-in `property` is the reverse: property setting and deletion needs to be explicitly implemented

Disabling the value can be achieved by subclassing `functools.cached_property` and overriding/implementing `__set__` and `__delete__` to raise:

    class immutable_cached_property(functools.cached_property):
        def __set__(self, instance, value):
            raise AttributeError("can't set attribute")

        def __delete__(self, instance):
            raise AttributeError("can't delete attribute")

Further reading:
- Defining descriptors: https://docs.python.org/3/reference/datamodel.html#implementing-descriptors
- Descriptor how-to: https://docs.python.org/3/howto/descriptor.html
- Class construction: https://docs.python.org/3/reference/datamodel.html#creating-the-class-object
History
Date User Action Args
2019-10-21 23:53:20Epic_Winksetrecipients: + Epic_Wink, docs@python
2019-10-21 23:53:20Epic_Winksetmessageid: <1571702000.84.0.0143851282892.issue38553@roundup.psfhosted.org>
2019-10-21 23:53:20Epic_Winklinkissue38553 messages
2019-10-21 23:53:20Epic_Winkcreate