8000 bpo-42781: Document the mechanics of cached_property from a user view… · python/cpython@c8a7b8f · GitHub
[go: up one dir, main page]

Skip to content

Commit c8a7b8f

Browse files
authored
bpo-42781: Document the mechanics of cached_property from a user viewpoint (GH-24031)
1 parent b5711c9 commit c8a7b8f

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

Doc/library/functools.rst

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,16 +62,26 @@ The :mod:`functools` module defines the following functions:
6262
Example::
6363

6464
class DataSet:
65+
6566
def __init__(self, sequence_of_numbers):
66-
self._data = sequence_of_numbers
67+
self._data = tuple(sequence_of_numbers)
6768

6869
@cached_property
6970
def stdev(self):
7071
return statistics.stdev(self._data)
7172

72-
@cached_property
73-
def variance(self):
74-
return statistics.variance(self._data)
73+
The mechanics of :func:`cached_property` are somewhat different from
74+
:func:`property`. A regular property blocks attribute writes unless a
75+
setter is defined. In contrast, a *cached_property* allows writes.
76+
77+
The *cached_property* decorator only runs on lookups and only when an
78+
attribute of the same name doesn't exist. When it does run, the
79+
*cached_property* writes to the attribute with the same name. Subsequent
80+
attribute reads and writes take precedence over the *cached_property*
81+
method and it works like a normal attribute.
82+
83+
The cached value can be cleared by deleting the attribute. This
84+
allows the *cached_property* method to run again.
7585

7686
Note, this decorator interferes with the operation of :pep:`412`
7787
key-sharing dictionaries. This means that instance dictionaries

0 commit comments

Comments
 (0)
0