简体   繁体   English

如何获取 python 函数的酸洗依赖项?

[英]How to get a python function's dependencies for pickling?

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

What is a good approach for determining a method's dependencies?确定方法依赖性的好方法是什么? For instance, similar to the above post, if I have a function f that uses methods g and y is there an easy way to get a reference to g and y dynamically?例如,类似于上面的帖子,如果我有一个使用方法 g 和 y 的 function f,是否有一种简单的方法可以动态获取对 g 和 y 的引用?

Further, I guess you would want this method to recurse down the entire function graph such that if y depended on z you could also bundle up z.此外,我想您可能希望此方法递归整个 function 图,这样如果 y 依赖于 z,您也可以捆绑 z。

I see that disco uses the following module for this: https://github.com/discoproject/disco/blob/master/lib/disco/worker/classic/modutil.py我看到迪斯科为此使用了以下模块: https://github.com/discoproject/disco/blob/master/lib/disco/worker/classic/modutil.py

Any other suggestions on how to tackle this?关于如何解决这个问题的任何其他建议? The disco approach seems to be module based so you potentially have to bundle up more than you need to actually execute the root method. disco 方法似乎是基于模块的,因此您可能需要捆绑比实际执行 root 方法所需的更多的东西。

To do this, I'd use dill , which can serialize almost anything in python. Dill also hassome good tools for helping you understand what is causing your pickling to fail when your code fails.为此,我将使用dill ,它几乎可以序列化 python 中的任何内容。Dill 还提供了一些很好的工具,可帮助您了解代码失败时导致酸洗失败的原因。

>>> 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)
>>> ...

If you absolutely wanted to, you could use dill's badobjects (or one of the other detection functions) to dive recursively into your object's reference chain, and pop out the unpickleable objects, instead of calling it at at every depth, as above.如果您确实想要,您可以使用 dill 的badobjects (或其他检测函数之一)递归地深入到您的对象的引用链中,并弹出 unpickleable 对象,而不是像上面那样在每个深度调用它。

Also, objgraph is a pretty handy compliment to the test suite too.此外, objgraph也是对测试套件的一个非常方便的补充。

>>> # visualize the references in your bad objects
>>> objgraph.show_refs(your_bad_object, filename='your_bad_object.png')

Or, as I mentioned in your above noted post, you can use dill to pickle the entire python session in one command.或者,正如我在上面提到的帖子中提到的,您可以使用 dill 在一个命令中腌制整个 python session。 That's a bit overkill for your question here, but it'd work too.这对于您在这里的问题有点矫枉过正,但它也会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM