0

我正在尝试foo(dti: DatetimeIndex)使用@functools.lru_cache()注释来记忆一个方法。但是,它抱怨TypeError: unhashable type: 'DatetimeIndex'.

由于DatetimeIndex对象是不可变的,所以应该有一种很好的方法将它们用作记忆的关键,对吧?

另外,DatetimeIndex定义一个哈希方法来简单地返回它会有什么问题id()

4

1 回答 1

-1

我最终编写了自己的装饰器,以便能够记住接受DataFrame对象(或Hashable对象,以防DataFrames 将来可散列)的方法,它看起来像这样:

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):
    ...
于 2017-05-31T22:00:16.563 回答