How python uses the decorator to cache function calls
This article is about how python uses the decorator to cache function calls. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Use the decorator to cache function calls
Have you ever written a function that performs expensive I _ swap O operations or some fairly slow recursion that might benefit from caching (storing) its results? If you do, then there is a simple solution, that is, to use functools's lru_cache:
From functools import lru_cache import requests @ lru_cache (maxsize=32) def get_with_cache (url): try: r = requests.get (url) return r.text except: return "Not Found" for url in ["https://google.com/"," https://martinheinz.dev/", "https://reddit.com/", "https://google.com/"," https://dev.to/martinheinz", "https://google.com/"]: get_with_cache (url) print (get_with_cache.cache_info ()) # CacheInfo (hits=2, misses=4, maxsize=32, currsize=4)
In this example, we use cacheable GET requests (up to 32 cached results). You can also see that we can use the cache_info method to check the cache information of the function. The decorator also provides a clear_cache method to invalidate the cached results.
I would also like to point out that this function should not be used with functions that have side effects or with functions that create mutable objects with each call.
Thank you for reading! This is the end of this article on "how to use the decorator to cache function calls in python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!