gpt4 book ai didi

python - 如何获取Python函数的pickle依赖项?

转载 作者:太空宇宙 更新时间:2023-11-03 19:20:00 24 4
gpt4 key购买 nike

作为这个问题的后续: How to pickle a python function with its dependencies?

确定方法依赖性的好方法是什么?例如,与上面的文章类似,如果我有一个使用方法 g 和 y 的函数 f ,是否有一种简单的方法可以动态获取对 g 和 y 的引用?

此外,我猜你会希望这个方法递归整个函数图,这样如果 y 依赖于 z,你也可以捆绑 z。

我看到迪斯科为此使用以下模块: https://github.com/discoproject/disco/blob/master/lib/disco/worker/classic/modutil.py

关于如何解决这个问题还有其他建议吗?迪斯科方法似乎是基于模块的,因此您可能必须捆绑比实际执行根方法所需的更多内容。

最佳答案

为此,我将使用 dill ,它几乎可以序列化 python 中的任何内容。莳萝还有some good tools帮助您了解当代码失败时导致 pickle 失败的原因。

>>> import dill
>>> dill.loads(dill.dumps(your_bad_object))
>>> ...
>>> # if you get a pickling error, use dill's tools to figure out a workaround
>>> dill.detect.badobjects(your_bad_object, depth=0)
>>> dill.detect.badobjects(your_bad_object, depth=1)
>>> ...

如果您绝对愿意,您可以使用 dill 的 badobjects(或其他检测函数之一)递归地深入到对象的引用链中,并弹出不可拾取的对象,而不是调用它在每个深度,如上所述。

此外,objgraph也是对测试套件的一个非常方便的补充。

>>> # visualize the references in your bad objects
>>> objgraph.show_refs(your_bad_object, filename='your_bad_object.png')
或者,正如我在上面提到的帖子中提到的,您可以使用 dill 在一个命令中 pickle 整个 python session 。对于你在这里的问题来说有点过分了,但它也有用。

关于python - 如何获取Python函数的pickle依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10082241/

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