Python:使用函数参数持久记忆函数的策略?

发布于 2025-01-06 18:20:49 字数 296 浏览 4 评论 0原文

我写了一个小类来持续记住一些昂贵的函数,这些函数对随机网络进行各种统计分析。

这些都是纯函数;所有数据都是不可变的。但是,某些函数将函数作为参数。

基于这些参数创建密钥是一个小问题,因为在 Python 中函数对象相等性相当于函数对象标识,即使函数实现没有更改,它也不会在会话之间持续存在。

我暂时通过使用函数名称作为字符串来解决这个问题,但是当人们开始考虑更改函数或匿名函数等的实现时,这会引发一系列问题。但我可能不是第一个担心此类事情的人。

有没有人有任何策略可以在Python中持久地记忆带有函数参数的函数?

I have written a little class to persistently memoize some expensive functions that do various statistical analyses of random networks.

These are all pure functions; all the data is immutable. However, some of the functions take functions as arguments.

Making keys based on these arguments is a small problem, since in Python function object equality is equivalent to function object identity, which does not persist between sessions, even if the function implementation does not change.

I am hacking around this for the time being by using the function name as a string, but this raises its own swarm of issues when one starts thinking about changing the implementation of the function or anonymous functions and so on. But I am probably not the first to worry about such things.

Does anybody have any strategies for persistently memoizing functions with function arguments in Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

肥爪爪 2025-01-13 18:20:49

一种选择是使用 marshal.dumps(function.func_code)

它将生成函数代码的字符串表示形式。这应该处理不断变化的实现和匿名函数。

One option would be to use marshal.dumps(function.func_code)

It'll produce a string representation for the code of the function. That should handle changing implementations and anonymous functions.

薆情海 2025-01-13 18:20:49

看看使用它作为

[getattr(func.__code__,s) 
 for s in ['co_argcount', 'co_cellvars', 'co_code', 'co_consts', 
           'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars',
           'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize',
           'co_varnames']
]

应该正确处理以任何方式更改实现的函数的标识......

Have a look at using this as the identity of the function

[getattr(func.__code__,s) 
 for s in ['co_argcount', 'co_cellvars', 'co_code', 'co_consts', 
           'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars',
           'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize',
           'co_varnames']
]

that should correctly handle changing the implementation in any way...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文