1 ===============================
3 ===============================
5 .. image:: https://badge.fury.io/py/cached-property.png
6 :target: http://badge.fury.io/py/cached-property
8 .. image:: https://travis-ci.org/pydanny/cached-property.png?branch=master
9 :target: https://travis-ci.org/pydanny/cached-property
11 .. image:: https://pypip.in/d/cached-property/badge.png
12 :target: https://pypi.python.org/pypi/cached-property
15 A cached-property for decorating methods in classes.
20 * Makes caching of time or computational expensive properties quick and easy.
21 * Because I got tired of copy/pasting this code from non-web project to non-web project.
22 * I needed something really simple that worked in Python 2 and 3.
27 Let's define a class with an expensive property. Every time you stay there the
30 .. code-block:: python
32 class Monopoly(object):
35 self.boardwalk_price = 500
39 # In reality, this might represent a database call or time
40 # intensive task like calling a third-party API.
41 self.boardwalk_price += 50
42 return self.boardwalk_price
46 .. code-block:: python
48 >>> monopoly = Monopoly()
49 >>> monopoly.boardwalk
51 >>> monopoly.boardwalk
54 Let's convert the boardwalk property into a `cached_property`.
57 .. code-block:: python
59 from cached_property import cached_property
61 class Monopoly(object):
64 self.boardwalk_price = 500
67 def cached_property(self):
68 # Again, this is a silly example. Don't worry about it, this is
69 # just an example for clarity.
70 self.boardwalk_price += 50
71 return self.boardwalk_price
73 Now when we run it the price stays at $550.
75 .. code-block:: python
77 >>> monopoly = Monopoly()
78 >>> monopoly.boardwalk
80 >>> monopoly.boardwalk
82 >>> monopoly.boardwalk
85 Why doesn't the value of `m.boardwalk` change? Because it's a **cached property**!
90 * Django, Werkzueg, Bottle, and Zope for having their own implementations. This package uses the Django version.
91 * Reinout Van Rees for pointing out the cached_property decorator to me.
92 * My awesome wife Audrey who created cookiecutter, which meant rolling this out took me just 15 minutes.