[英]How to Import Class From Inside the Main function of another file?
[英]How to dump a function with import inside
我正在嘗試將函數轉儲到一個文件中,以便我可以在其他地方使用這個文件/函數。 我選擇dill
而不是pickle
,因為我需要依賴項。 但是,如果 function 內部有導入,則dill
不起作用。 例如:
def func():
import numpy
import dill
dill.settings['recurse'] = True
with open("test.pickle","wb") as f:
dill.dump(func,f)
當我重新啟動並加載 function 時,出現此錯誤,
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()
之類的函數。 有沒有辦法轉儲具有導入和依賴項的函數? 我覺得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
設置意味着通過全局字典遞歸跟蹤引用,但不存儲整個全局字典。 dill
的默認設置是在 pickle function 時存儲所有全局字典。因此, recurse
可以使 pickle 變小,但它們也可能由於缺少引用而失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.