aboutsummaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorThomas Kemmer <tkemmer@computer.org>2014-09-22 17:59:04 +0200
committerThomas Kemmer <tkemmer@computer.org>2014-09-23 11:01:28 +0200
commita8d2b038f3331da782c73ed5755dc3f3d363d8fa (patch)
treed73ac036958607f8d9d9509ea8f04d558f5073b8 /docs
parent78408a1c1a9018468941075c1b991161505bcbe1 (diff)
downloadcachetools-a8d2b038f3331da782c73ed5755dc3f3d363d8fa.tar.gz
Resolve #8: Rewrite @cachedmethod example to use per-object cache
Diffstat (limited to 'docs')
-rw-r--r--docs/index.rst51
1 files changed, 31 insertions, 20 deletions
diff --git a/docs/index.rst b/docs/index.rst
index 77941b9..93dc71c 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -150,26 +150,37 @@ Method Decorators
.. decorator:: cachedmethod(cache, typed=False)
`cache` specifies a function of one argument that, when passed
- :const:`self`, will return the cache object for the instance or
- class. See the `Function Decorators`_ section for details on the
- `typed` argument.
-
- Python 3 example of a shared (class) LRU cache for static web
- content::
-
- class CachedPEPs(object):
-
- cache = LRUCache(maxsize=32)
-
- @cachedmethod(operator.attrgetter('cache'))
- def get_pep(self, num):
- """Retrieve text of a Python Enhancement Proposal"""
- resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
- try:
- with urllib.request.urlopen(resource) as s:
- return s.read()
- except urllib.error.HTTPError:
- return 'Not Found'
+ :const:`self`, will return a *cache* for the respective instance or
+ class. Multiple methods of an object or class may share the same
+ cache.
+
+ One advantage of the `@cachedmethod` decorator over the similar
+ function decorators is that cache properties such as `maxsize` can
+ be set at runtime::
+
+ import operator
+ import urllib.request
+
+ from cachetools import LRUCache, cachedmethod
+
+ class CachedPEPs(object):
+
+ def __init__(self, cachesize):
+ self.cache = LRUCache(maxsize=cachesize)
+
+ @cachedmethod(operator.attrgetter('cache'))
+ def get_pep(self, num):
+ """Retrieve text of a Python Enhancement Proposal"""
+ url = 'http://www.python.org/dev/peps/pep-%04d/' % num
+ with urllib.request.urlopen(url) as s:
+ return s.read()
+
+ peps = CachedPEPs(cachesize=10)
+ print("PEP #1: %s" % peps.get_pep(1))
+
+ Note that no locking will be performed on the object returned by
+ `cache(self)`, so dealing with concurrent access is entirely the
+ responsibility of the user.
.. _mutable: http://docs.python.org/dev/glossary.html#term-mutable