Python 如何转储包含导入的函数

Python 如何转储包含导入的函数,python,pickle,dump,dill,Python,Pickle,Dump,Dill,我试图将函数转储到一个文件中,以便在其他地方使用此文件/函数。我选择dill而不是pickle,因为我需要依赖关系。但是,如果函数内部有导入,则dill不起作用。例如: def func(): import numpy import dill dill.settings['recurse'] = True with open("test.pickle","wb") as f: dill.dump(func,f) 当我重新启动并重新加载函数时,会出现此错误 import di

我试图将函数转储到一个文件中,以便在其他地方使用此文件/函数。我选择dill而不是pickle,因为我需要依赖关系。但是,如果函数内部有导入,则dill不起作用。例如:

def func():
    import numpy

import dill
dill.settings['recurse'] = True 
with open("test.pickle","wb") as f:
    dill.dump(func,f)
当我重新启动并重新加载函数时,会出现此错误

import dill 
func = dill.load(open("test.pickle"))
func()
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input> in <module>()
      1 import dill
      2 func = dill.load(open("test.pickle"))
----> 3 func()

<ipython-input> in func()

ImportError: __import__ not found
导入dill
func=dill.load(打开(“test.pickle”))
func()
---------------------------------------------------------------------------
ImportError回溯(最近一次呼叫最后一次)
在()
1进口莳萝
2 func=静载荷(打开(“试验酸洗”))
---->3 func()
在func()中
导入错误:\未找到导入
如果我使用
pickle
转储,则此示例有效,但
pickle
似乎不会递归保存依赖项,因此无法保存
def fun1():return fun2()
之类的函数。
是否有一种方法可以转储同时具有导入和依赖项的函数?我觉得pickle或dill只能做一半。

我是dill的作者。我相信dill也应该适合你:

$ python
Python 3.6.10 (default, Dec 21 2019, 11:39:07) 
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> def func():
...   import numpy
... 
>>> import dill
>>> 
>>> with open('XXX.pkl', 'wb') as f:
...   dill.dump(func, f)
... 
>>> 

$ python
Python 3.6.10 (default, Dec 21 2019, 11:39:07) 
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> func = dill.load(open('XXX.pkl', 'rb'))
>>> func()
>>> 
recurse
设置意味着通过全局dict递归跟踪引用,但不存储整个全局dict。
dill
的默认设置是在酸洗函数时存储所有全局dict。因此,
recurse
可以使pickle更小,但也可能由于缺少引用而失败