Skip to Content
Secret Recipes of the Python Ninja
book

Secret Recipes of the Python Ninja

by Cody Jackson
May 2018
Intermediate to advanced content levelIntermediate to advanced
380 pages
9h 37m
English
Packt Publishing
Content preview from Secret Recipes of the Python Ninja

How to do it...

A common use of decorators, outside of frameworks, is to memoize functions. Memoization caches the results of a function call to a dictionary; if the function is called again with the same arguments, the result is pulled from the cache rather than rerunning the function again. Many memoization functions and decorators have been created, but most don't preserve the signature. The following examples are taken from the decorator module's documentation (http://decorator.readthedocs.io/en/latest/tests.documentation.html):

  1. A memoization decorator can be written to cache the input arguments to a dictionary (memoize_dec.py):
        import functools        import time         def memoize_uw(func):
            func.cache = {}

            def memoize(*args, **kw):
                if kw:  # frozenset ...
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

The Expanding World of Python

The Expanding World of Python

Dane Hillard

Publisher Resources

ISBN: 9781788294874Supplemental Content