Better @memoized
decorator.
This commit is contained in:
parent
da98b07624
commit
92f398a897
@ -26,6 +26,7 @@
|
|||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
import functools
|
import functools
|
||||||
|
import collections
|
||||||
import inspect
|
import inspect
|
||||||
|
|
||||||
# Ignore emacs backups when listing modules
|
# Ignore emacs backups when listing modules
|
||||||
@ -170,16 +171,32 @@ def has_method(cls, name):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def memoized(obj):
|
class memoized(object):
|
||||||
"""Decorator that caches the results of a function, storing them
|
"""Decorator that caches the results of a function, storing them
|
||||||
in an attribute of that function."""
|
in an attribute of that function."""
|
||||||
cache = obj.cache = {}
|
def __init__(self, func):
|
||||||
@functools.wraps(obj)
|
self.func = func
|
||||||
def memoizer(*args, **kwargs):
|
self.cache = {}
|
||||||
if args not in cache:
|
|
||||||
cache[args] = obj(*args, **kwargs)
|
|
||||||
return cache[args]
|
def __call__(self, *args):
|
||||||
return memoizer
|
if not isinstance(args, collections.Hashable):
|
||||||
|
# Not hashable, so just call the function.
|
||||||
|
return self.func(*args)
|
||||||
|
|
||||||
|
if args not in self.cache:
|
||||||
|
self.cache[args] = self.func(*args)
|
||||||
|
return self.cache[args]
|
||||||
|
|
||||||
|
|
||||||
|
def __get__(self, obj, objtype):
|
||||||
|
"""Support instance methods."""
|
||||||
|
return functools.partial(self.__call__, obj)
|
||||||
|
|
||||||
|
|
||||||
|
def clear(self):
|
||||||
|
"""Expunge cache so that self.func will be called again."""
|
||||||
|
self.cache.clear()
|
||||||
|
|
||||||
|
|
||||||
def list_modules(directory, **kwargs):
|
def list_modules(directory, **kwargs):
|
||||||
|
Loading…
Reference in New Issue
Block a user