Skip to Content
Mastering Object-oriented Python
book

Mastering Object-oriented Python

by Steven F. Lott
April 2014
Beginner to intermediate
634 pages
15h 22m
English
Packt Publishing
Content preview from Mastering Object-oriented Python

Using functools for memoization

The Python library includes a memoization decorator in the functools module. We can use this module instead of creating our own callable object.

We can use it as follows:

from functools import lru_cache
@lru_cache(None)
def pow6( x, n ):
    if n == 0: return 1
    elif n % 2 == 1:
        return pow6(x, n-1)*x
    else: # n % 2 == 0:
        t= pow6(x, n//2)
        return t*t

This defined a function, pow6(), which is decorated with a Least Recently Used (LRU) cache. Previous requests are stored in a memoization cache. The requests are tracked in the cache, and the size is limited. The idea behind an LRU cache is that the most recently made requests are kept and the least recently made requests are quietly purged.

Using timeit, we can see that 10,000 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Object-Oriented Python - Second Edition

Mastering Object-Oriented Python - Second Edition

Steven F. Lott

Publisher Resources

ISBN: 9781783280971Supplemental Content