Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an alias to functools.lru_cache for memoization?

To add memoization to functions in Python, the functools.lru_cache() decorator can be used:

import functools

@functools.lru_cache(maxsize=None)
def my_func():
    ...

However, I would like to define the following alias to the above use of functools.lru_cache() to make the code more readable:

@memoize
def my_func():
    ...

My question is: how to define such an alias? The following piece of code doesn't work:

memoize = functools.partial(functools.lru_cache, maxsize=None)
like image 220
s3rvac Avatar asked Mar 18 '23 07:03

s3rvac


1 Answers

You don't need the functools.partial because it is already setup to take two calls. Just call it once:

memoize = functools.lru_cache(maxsize=None)

then use the alias as a decorator:

@memoize
def my_func():
    ...
like image 51
Andrew Johnson Avatar answered Apr 02 '23 02:04

Andrew Johnson