Skip to content

Instantly share code, notes, and snippets.

@NatiAris
Created August 27, 2018 20:00
Show Gist options
  • Select an option

  • Save NatiAris/ed0abc33594352a16d745b4320750f58 to your computer and use it in GitHub Desktop.

Select an option

Save NatiAris/ed0abc33594352a16d745b4320750f58 to your computer and use it in GitHub Desktop.
A simple decorator adding memoization to a function. Only works with positional arguments. Way too simplistic to have a limit on cache size, so be careful.
import functools
def memoize(outer_func):
"""Memoize everything."""
@functools.wraps(outer_func)
def inner_func(*args, _cache={}):
if args in _cache:
return _cache[args]
_cache[args] = outer_func(*args)
return _cache[args]
return inner_func
@NatiAris
Copy link
Author

NatiAris commented Sep 4, 2018

Can access the accumulated cache through func.__kwdefaults__['_cache'] and re-use by passing as _cache keyword argument.

@memoize
def f(n):
    pass

cache = f.__kwdefaults__['_cache']  # Note: you're not copying the dict, so modifying it will affect the function
f(42, _cache=cache)  # _cache argument won't be shown in the docstring

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment