gpt4 book ai didi

python-3.x - 如何忽略functools中的参数。 lru_cache?

转载 作者:行者123 更新时间:2023-12-04 19:38:42 24 4
gpt4 key购买 nike

这是我要通过缓存增强的功能的框架,因为执行RPC(远程过程调用)涉及到其他主机的TCP连接。

def rpc(rpc_server, rpc_func, arg):
return rpc_server.do_rpc(rpc_func, arg)

但是,最简单的装饰方式是:
@functools.lru_cache()

不能正常工作,因为 rpc_server对象来来去去,并且缓存应该忽略此参数。

我可以自己编写一个简单的内存代码。没问题。实际上,我看不到其他解决方案。

我无法以可以应用 的方式重写@lru_cache()装饰器,并且 rpc_server将作为参数传递(即,我不想让 rpc_server成为全局变量)。是否可以?

最佳答案

我发布这个只是为了完善。欢迎发表评论,但请不要投票。

我从我的问题中找到了一种满足条件的方法。我不会使用此代码。但是它显示了Python的灵活性。

import functools

class BlackBox:
"""All BlackBoxes are the same."""
def __init__(self, contents):
# TODO: use a weak reference for contents
self._contents = contents

@property
def contents(self):
return self._contents

def __eq__(self, other):
return isinstance(other, type(self))

def __hash__(self):
return hash(type(self))

@functools.lru_cache()
def _cached_func(blackbox, real_arg):
print("called with args:", blackbox.contents, real_arg)
return real_arg + 1000

def cached_func(ignored_arg, real_arg):
# ignored means ignored by the cache
return _cached_func(BlackBox(ignored_arg), real_arg)

cached_func("foo", 1) # cache miss
cached_func("bar", 1) # cache hit

cached_func("bar", 2) # cache miss
cached_func("foo", 2) # cache hit

关于python-3.x - 如何忽略functools中的参数。 lru_cache?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38940954/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com