Skip to content

Commit 427cb0a

Browse files
bpo-42127: Document effect of cached_property on key-sharing dictionaries (GH-22930) (GH-22955)
1 parent 2d49389 commit 427cb0a

File tree

1 file changed

+24
-9
lines changed

1 file changed

+24
-9
lines changed

Doc/library/functools.rst

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -73,16 +73,31 @@ The :mod:`functools` module defines the following functions:
7373
def variance(self):
7474
return statistics.variance(self._data)
7575

76-
.. versionadded:: 3.8
76+
Note, this decorator interferes with the operation of :pep:`412`
77+
key-sharing dictionaries. This means that instance dictionaries
78+
can take more space than usual.
7779

78-
.. note::
80+
Also, this decorator requires that the ``__dict__`` attribute on each instance
81+
be a mutable mapping. This means it will not work with some types, such as
82+
metaclasses (since the ``__dict__`` attributes on type instances are
83+
read-only proxies for the class namespace), and those that specify
84+
``__slots__`` without including ``__dict__`` as one of the defined slots
85+
(as such classes don't provide a ``__dict__`` attribute at all).
86+
87+
If a mutable mapping is not available or if space-efficient key sharing
88+
is desired, an effect similar to :func:`cached_property` can be achieved
89+
by a stacking :func:`property` on top of :func:`cache`::
7990

80-
This decorator requires that the ``__dict__`` attribute on each instance
81-
be a mutable mapping. This means it will not work with some types, such as
82-
metaclasses (since the ``__dict__`` attributes on type instances are
83-
read-only proxies for the class namespace), and those that specify
84-
``__slots__`` without including ``__dict__`` as one of the defined slots
85-
(as such classes don't provide a ``__dict__`` attribute at all).
91+
class DataSet:
92+
def __init__(self, sequence_of_numbers):
93+
self._data = sequence_of_numbers
94+
95+
@property
96+
@cache
97+
def stdev(self):
98+
return statistics.stdev(self._data)
99+
100+
.. versionadded:: 3.8
86101

87102

88103
.. function:: cmp_to_key(func)
@@ -651,4 +666,4 @@ callable, weak referencable, and can have attributes. There are some important
651666
differences. For instance, the :attr:`~definition.__name__` and :attr:`__doc__` attributes
652667
are not created automatically. Also, :class:`partial` objects defined in
653668
classes behave like static methods and do not transform into bound methods
654-
during instance attribute look-up.
669+
during instance attribute look-up.

0 commit comments

Comments
 (0)