我正在尝试foo(dti: DatetimeIndex)
使用@functools.lru_cache()
注释来记忆一个方法。但是,它抱怨TypeError: unhashable type: 'DatetimeIndex'
.
由于DatetimeIndex
对象是不可变的,所以应该有一种很好的方法将它们用作记忆的关键,对吧?
另外,DatetimeIndex
定义一个哈希方法来简单地返回它会有什么问题id()
?
我正在尝试foo(dti: DatetimeIndex)
使用@functools.lru_cache()
注释来记忆一个方法。但是,它抱怨TypeError: unhashable type: 'DatetimeIndex'
.
由于DatetimeIndex
对象是不可变的,所以应该有一种很好的方法将它们用作记忆的关键,对吧?
另外,DatetimeIndex
定义一个哈希方法来简单地返回它会有什么问题id()
?
我最终编写了自己的装饰器,以便能够记住接受DataFrame
对象(或Hashable
对象,以防DataFrame
s 将来可散列)的方法,它看起来像这样:
def my_memoize(func):
# TODO use an LRU cache so we don't grow forever
cache = {}
def decorating_function(self, arg):
key = arg if isinstance(arg, collections.Hashable) else id(arg)
key = (self, key)
if key in cache:
return cache[key]
value = func(self, arg)
cache[key] = value
return value
return decorating_function
我像这样使用它:
@my_memoize
def calculate_stuff(self, df):
...