Commit 1d796473 authored by Leo Pound Singer's avatar Leo Pound Singer

Implement memoized() using stdlib functools.lru_cache()

Original: e69ab5455d179807a90f607309649ead20d0f2fb
parent 3f75b6c8
......@@ -27,37 +27,37 @@ from collections import Hashable
from astropy.utils.misc import NumpyRNGContext
def memoized(func):
"""Memoize a function or class by caching its return values for any given
arguments."""
cache = {}
# FIXME: In Python 3.4, use inspect.getcallargs to bind function arguments.
# This will allow us to handle default arguments better.
# (Though inspect.getcallargs was added in Python 2.7, it won't work with
# built-in functions or functions from C extensions until Python 3.4.
# See https://bugs.python.org/issue17481.)
@wraps(func)
def memo(*args, **kwargs):
# Create a key out of the arguments.
key = (args, frozenset(kwargs.items()))
if isinstance(args, Hashable): # The key is immutable.
try:
# Look up the return value for these arguments.
ret = cache[key]
except KeyError:
# Not found; invoke function and store return value.
ret = cache[key] = func(*args, **kwargs)
else: # The key is mutable. We can't cache it.
ret = func(*args, **kwargs)
# Done!
return ret
# Return wrapped function.
return memo
try:
from functools import lru_cache
except ImportError:
# FIXME: Remove this when we drop support for Python < 3.2.
def memoized(func):
"""Memoize a function or class by caching its return values for any
given arguments."""
cache = {}
@wraps(func)
def memo(*args, **kwargs):
# Create a key out of the arguments.
key = (args, frozenset(kwargs.items()))
if isinstance(args, Hashable): # The key is immutable.
try:
# Look up the return value for these arguments.
ret = cache[key]
except KeyError:
# Not found; invoke function and store return value.
ret = cache[key] = func(*args, **kwargs)
else: # The key is mutable. We can't cache it.
ret = func(*args, **kwargs)
# Done!
return ret
# Return wrapped function.
return memo
else:
memoized = lru_cache(maxsize=None)
def with_numpy_random_seed(func, seed=0):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment