Skip to content

Instantly share code, notes, and snippets.

@celeroncoder
Created March 30, 2021 04:57
Show Gist options
  • Save celeroncoder/64bc6bb51e4decd6c47c3ccc6f67d4d3 to your computer and use it in GitHub Desktop.
Save celeroncoder/64bc6bb51e4decd6c47c3ccc6f67d4d3 to your computer and use it in GitHub Desktop.
Cache Decorator in Python

Cache Decorator in Python

Description

  • In this directory it holds the implementation of cache Decorator in python.
  • We can use this decorator when we are using more computational power on stuff that has already been done.

Cache Decorator

  • Cache Decorator is a default Decorator in python from the built-in lib functools.

  • It stores the previously computed data and use it for further.

  • Uses a bit more memory but saves in computational power of the hardware.

Example

  • Here is a bad implementation of fibonacci function that gives the nth fibonacci number using recursion.

     def fib(n):
     if n <= 1:
     	return n
     return fib(n-1) + fib(n-2)
  • We create a main function that loops through a range of number, let's say, 400(0-399) and prints the index and the fibonacci number at that index.

     def main():
     for i in range(400):
     	print(f'|> {i} >> {fib(i)}')
     print("done")
  • The implementation of this function use high computational power and recomputes every number again and again that makes it very inefficient, it takes forever to complete, the time increases as the index does.

  • Now, we use the cache decorator on top of the fibonacci function that stores the computed data and then reuse it if required.

     from functools import cache
     @cache
     def fib(n):
     	if n <= 1:
     		return n
     	return fib(n-1) + fib(n-2)
  • Now, the function auto-cache computed data and it finishes implementation in no time.

  • To save memory we can use the lru_cache decorator that takes up a max length to save the previously computed data rather than storing them all like in the cache operator.

     from functools import cache, lru_cache
     @lru_cache(maxsize=5)
     def fib(n):
     	if n <= 1:
     		return n
     	return fib(n-1) + fib(n-2)
from functools import cache, lru_cache
@lru_cache(maxsize=5)
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
def main():
for i in range(400):
print(f'|> {i} >> {fib(i)}')
print("done")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment