Skip to Content
Modern Python Standard Library Cookbook
book

Modern Python Standard Library Cookbook

by Alessandro Molina
August 2018
Intermediate to advanced
366 pages
10h 14m
English
Packt Publishing
Content preview from Modern Python Standard Library Cookbook

How it works...

Whenever the function is invoked, functools.lru_cache saves the returned value together with the provided arguments.

The next time the function will be called, the arguments are searched in the saved arguments and, if they are found, the previously returned value is provided instead of calling the function.

This, in fact, changes the cost of calling our function to being just the cost of a lookup in a dictionary.

So the first time we call fibonacci(5), it gets computed, then next time it will be called, it will do nothing and the value previously stored for 5 will be returned. As fibonacci(6) has to call fibonacci(5) to be able to compute, it's easy to see how we provided a major performance benefit for any fibonacci(n) where ...

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

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Matthew Wilkes

Publisher Resources

ISBN: 9781788830829Supplemental Content