Skip to content

bpo-42781: Document the mechanics of cached_property from a user viewpoint #24031

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 1, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions Doc/library/functools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down