Python 3.x 当参数是对象实例且缓存需要查看实例属性时,如何lru_缓存函数?

Python 3.x 当参数是对象实例且缓存需要查看实例属性时,如何lru_缓存函数?,python-3.x,caching,lru,Python 3.x,Caching,Lru,我试图在一个函数上实现lru_缓存,该函数将python对象作为参数。仅当函数的参数属性未更改时,该函数才应返回缓存值。但是,看起来lru_缓存只对函数参数进行“浅层查看”,以查看发生了哪些更改,并忽略了任何属性更改 例如,在下面的calculate函数中,该函数用lru\u cache修饰,它接收单元格实例并根据实例的属性返回计算结果 from functools import lru_cache class Cell: def __init__(self, x, y):

我试图在一个函数上实现lru_缓存,该函数将python对象作为参数。仅当函数的参数属性未更改时,该函数才应返回缓存值。但是,看起来lru_缓存只对函数参数进行“浅层查看”,以查看发生了哪些更改,并忽略了任何属性更改

例如,在下面的
calculate
函数中,该函数用
lru\u cache
修饰,它接收单元格实例并根据实例的属性返回计算结果

from functools import lru_cache

class Cell:

    def __init__(self, x, y):
        self.x =x
        self.y =y


@lru_cache()
def calculate(cell):
    return cell.x + cell.y
运行此操作时:

if __name__ == '__main__':

    cellA = Cell(1,2)
    print(calculate(cellA))
    #returns 3 correctly

    #let's change cellA's attribute of x to something else
    cellA.x = 10

    print(calculate(cellA))
    #also returns 3, but should return 12!
我希望对函数的第二次调用实际使用缓存值,因为属性x现在已经更改

一个非常不雅观的解决方法是将“伪参数”传递给calculate函数,如下所示:

@lru_cache()
def calculate(cell, prec):
    return cell.x + cell.y

if __name__ == '__main__':

    cellA = Cell(1,2)
    print(calculate(cellA, prec=cellA.x))
    #returns 3

    #let's change cellA's attribute of x to something else
    cellA.x = 10


    print(calculate(cellA, prec=cellA.x))
    #now returns 12!
上述方法可行,但似乎是一种不好的方法