summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRaymond Hettinger <rhettinger@users.noreply.github.com>2021-01-01 01:05:58 (GMT)
committerGitHub <noreply@github.com>2021-01-01 01:05:58 (GMT)
commitc8a7b8fa1b5f9a6d3052db792018dc27c5a3a794 (patch)
treee68d27cdf8347bd68a6c7de843a85ffa55a064f0
parentb5711c940f70af89f2b4cf081a3fcd83924f3ae7 (diff)
downloadcpython-c8a7b8fa1b5f9a6d3052db792018dc27c5a3a794.zip
cpython-c8a7b8fa1b5f9a6d3052db792018dc27c5a3a794.tar.gz
cpython-c8a7b8fa1b5f9a6d3052db792018dc27c5a3a794.tar.bz2
bpo-42781: Document the mechanics of cached_property from a user viewpoint (GH-24031)
-rw-r--r--Doc/library/functools.rst18
1 files changed, 14 insertions, 4 deletions
diff --git a/Doc/library/functools.rst b/Doc/library/functools.rst
index 75c9d41..e981bcd 100644
--- a/Doc/library/functools.rst
+++ b/Doc/library/functools.rst
@@ -62,16 +62,26 @@ The :mod:`functools` module defines the following functions:
Example::
class DataSet:
+
def __init__(self, sequence_of_numbers):
- self._data = sequence_of_numbers
+ self._data = tuple(sequence_of_numbers)
@cached_property
def stdev(self):
return statistics.stdev(self._data)
- @cached_property
- def variance(self):
- return statistics.variance(self._data)
+ The mechanics of :func:`cached_property` are somewhat different from
+ :func:`property`. A regular property blocks attribute writes unless a
+ setter is defined. In contrast, a *cached_property* allows writes.
+
+ The *cached_property* decorator only runs on lookups and only when an
+ attribute of the same name doesn't exist. When it does run, the
+ *cached_property* writes to the attribute with the same name. Subsequent
+ attribute reads and writes take precedence over the *cached_property*
+ method and it works like a normal attribute.
+
+ The cached value can be cleared by deleting the attribute. This
+ allows the *cached_property* method to run again.
Note, this decorator interferes with the operation of :pep:`412`
key-sharing dictionaries. This means that instance dictionaries