Skip to content

Commit 071c220

Browse files
committed
Fix #326: Improve "CachedReferences" example.
1 parent 0b10b8d commit 071c220

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

docs/index.rst

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,9 @@ often called with the same arguments:
495495

496496
.. testcode::
497497

498+
from cachetools.keys import hashkey
499+
from functools import partial
500+
498501
class CachedPEPs:
499502

500503
def __init__(self, cachesize):
@@ -523,35 +526,44 @@ often called with the same arguments:
523526

524527
.. testcode::
525528

529+
from cachetools.keys import methodkey
530+
from functools import partial
531+
526532
class CachedReferences:
527533

528534
def __init__(self, cachesize):
529535
self.cache = LRUCache(maxsize=cachesize)
530536

531-
@cachedmethod(lambda self: self.cache, key=partial(hashkey, 'pep'))
537+
@cachedmethod(lambda self: self.cache, key=partial(methodkey, method='pep'))
532538
def get_pep(self, num):
533539
"""Retrieve text of a Python Enhancement Proposal"""
534540
url = 'http://www.python.org/dev/peps/pep-%04d/' % num
535541
with urllib.request.urlopen(url) as s:
536542
return s.read()
537543

538-
@cachedmethod(lambda self: self.cache, key=partial(hashkey, 'rfc'))
544+
@cachedmethod(lambda self: self.cache, key=partial(methodkey, method='rfc'))
539545
def get_rfc(self, num):
540546
"""Retrieve text of an IETF Request for Comments"""
541547
url = 'https://tools.ietf.org/rfc/rfc%d.txt' % num
542548
with urllib.request.urlopen(url) as s:
543549
return s.read()
544550

545551
docs = CachedReferences(cachesize=100)
546-
print("PEP #1: %s" % docs.get_pep(1))
547-
print("RFC #1: %s" % docs.get_rfc(1))
552+
print("PEP #20: %s" % docs.get_pep(20))
553+
print("RFC #20: %s" % docs.get_rfc(20))
554+
assert len(docs.cache) == 2
548555

549556
.. testoutput::
550557
:hide:
551558
:options: +ELLIPSIS
552559

553-
PEP #1: ...
554-
RFC #1: ...
560+
PEP #20: ...
561+
RFC #20: ...
562+
563+
564+
Note how keyword arguments are used for :func:`functools.partial` to
565+
avoid issues with :func:`methodkey` skipping its initial `self`
566+
argument.
555567

556568

557569
*****************************************************************

0 commit comments

Comments
 (0)