如何在内部导入导入功能

时间:2020-04-25 00:18:52

标签: 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 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

如果我使用pickle进行转储,则此示例有效,但是pickle似乎没有递归保存依赖项,因此我无法保存类似def fun1(): return fun2()的函数。 有没有一种方法可以同时导入和依赖转储函数?我觉得pickledill只做一半。

1 个答案:

答案 0 :(得分:1)

我是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设置意味着通过全局字典递归地跟踪引用,但不存储整个全局字典。 dill的默认设置是在腌制函数时存储所有全局字典。因此,recurse可以使泡菜变小,但是由于缺少参考,泡菜也会失败。