Bump to 0.1.2
[cached-property.git] / README.rst
1 ===============================
2 cached-property
3 ===============================
4
5 .. image:: https://badge.fury.io/py/cached-property.png
6 :target: http://badge.fury.io/py/cached-property
7
8 .. image:: https://travis-ci.org/pydanny/cached-property.png?branch=master
9 :target: https://travis-ci.org/pydanny/cached-property
10
11 .. image:: https://pypip.in/d/cached-property/badge.png
12 :target: https://pypi.python.org/pypi/cached-property
13
14
15 A cached-property for decorating methods in classes.
16
17 Why?
18 -----
19
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.
23
24 How to use it
25 --------------
26
27 Let's define a class with an expensive property. Every time you stay there the
28 price goes up by $50!
29
30 .. code-block:: python
31
32 class Monopoly(object):
33
34 def __init__(self):
35 self.boardwalk_price = 500
36
37 @property
38 def boardwalk(self):
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
43
44 Now run it:
45
46 .. code-block:: python
47
48 >>> monopoly = Monopoly()
49 >>> monopoly.boardwalk
50 550
51 >>> monopoly.boardwalk
52 600
53
54 Let's convert the boardwalk property into a `cached_property`.
55
56
57 .. code-block:: python
58
59 from cached_property import cached_property
60
61 class Monopoly(object):
62
63 def __init__(self):
64 self.boardwalk_price = 500
65
66 @property
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
72
73 Now when we run it the price stays at $550.
74
75 .. code-block:: python
76
77 >>> monopoly = Monopoly()
78 >>> monopoly.boardwalk
79 550
80 >>> monopoly.boardwalk
81 550
82 >>> monopoly.boardwalk
83 550
84
85 Why doesn't the value of `m.boardwalk` change? Because it's a **cached property**!
86
87 Credits
88 --------
89
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.