New submission from Laurie Opperman <laurie_opper...@hotmail.com>:

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

----------
assignee: docs@python
components: Documentation, Library (Lib)
messages: 355110
nosy: Epic_Wink, docs@python
priority: normal
severity: normal
status: open
title: Document functools.cached_property supports value updating and clearing
type: enhancement
versions: Python 3.8

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue38553>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to