summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorCarl Meyer <carl@oddbird.net>2018-08-28 07:11:56 (GMT)
committerNick Coghlan <ncoghlan@gmail.com>2018-08-28 07:11:56 (GMT)
commitd658deac6060ee92b449a3bf424b460eafd99f3e (patch)
treeb20a3a288b17dd17fbd5e555f139b2c1df80bcb7 /Doc
parent216b745eafa7cd4a683a8405dcfbd7f5567f504c (diff)
downloadcpython-d658deac6060ee92b449a3bf424b460eafd99f3e.zip
cpython-d658deac6060ee92b449a3bf424b460eafd99f3e.tar.gz
cpython-d658deac6060ee92b449a3bf424b460eafd99f3e.tar.bz2
bpo-21145: Add cached_property decorator in functools (#6982)
Robust caching of calculated properties is harder than it looks at first glance, so add a solid, well-tested implementation to the standard library.
Diffstat (limited to 'Doc')
-rw-r--r--Doc/library/functools.rst33
1 files changed, 33 insertions, 0 deletions
diff --git a/Doc/library/functools.rst b/Doc/library/functools.rst
index 5e278f9..1b94f33 100644
--- a/Doc/library/functools.rst
+++ b/Doc/library/functools.rst
@@ -20,6 +20,39 @@ function for the purposes of this module.
The :mod:`functools` module defines the following functions:
+.. decorator:: cached_property(func)
+
+ Transform a method of a class into a property whose value is computed once
+ and then cached as a normal attribute for the life of the instance. Similar
+ to :func:`property`, with the addition of caching. Useful for expensive
+ computed properties of instances that are otherwise effectively immutable.
+
+ Example::
+
+ class DataSet:
+ def __init__(self, sequence_of_numbers):
+ self._data = sequence_of_numbers
+
+ @cached_property
+ def stdev(self):
+ return statistics.stdev(self._data)
+
+ @cached_property
+ def variance(self):
+ return statistics.variance(self._data)
+
+ .. versionadded:: 3.8
+
+ .. note::
+
+ This decorator requires that the ``__dict__`` attribute on each instance
+ be a mutable mapping. This means it will not work with some types, such as
+ metaclasses (since the ``__dict__`` attributes on type instances are
+ read-only proxies for the class namespace), and those that specify
+ ``__slots__`` without including ``__dict__`` as one of the defined slots
+ (as such classes don't provide a ``__dict__`` attribute at all).
+
+
.. function:: cmp_to_key(func)
Transform an old-style comparison function to a :term:`key function`. Used