如何转储包含导入的函数

2024-06-16 13:21:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将函数转储到一个文件中,以便在其他地方使用此文件/函数。我选择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只做了一半


Tags: 文件函数intestimportinputdef地方
1条回答
网友
1楼 · 发布于 2024-06-16 13:21:25

我是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变小,但也可能由于缺少引用而失败

相关问题 更多 >