Python:使用函数参数持久记忆函数的策略?
我写了一个小类来持续记住一些昂贵的函数,这些函数对随机网络进行各种统计分析。
这些都是纯函数;所有数据都是不可变的。但是,某些函数将函数作为参数。
基于这些参数创建密钥是一个小问题,因为在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种选择是使用 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.
看看使用它作为
应该正确处理以任何方式更改实现的函数的标识......
Have a look at using this as the identity of the function
that should correctly handle changing the implementation in any way...