通过 dill 使用全局变量序列化一个 Python 方法
Serialize a Python method with global variables by dill
这是一个示例代码,其中 FLAG
是一个全局变量。方法 A.func
对我来说是一个黑盒子,所以我不知道它在序列化之前调用 FLAG
。
import dill as pickle
FLAG = 100
class A:
def func(self):
print FLAG * 10
a = A()
dump = pickle.dumps(a.func)
del FLAG
foo = pickle.loads(dump) <-- fail here "NameError: global name 'FLAG' is not defined"
foo()
相关问题:
- Serialize a python function with dependencies
- How to pickle a python function with its dependencies?
最实用的解决方案是使用 cloudpickle
。但是好像dill
比cloudpickle
更健壮。所以我想坚持使用 dill
或其他成熟的 picklers。
如果需要,我不介意自己修改一些 dill
代码。
提前感谢您的帮助:)
我是 dill
作者。如果您使用 recurse
设置,它会起作用,它处理全局变量的方式与 cloudpickle
处理全局变量的方式非常相似。
>>> import dill
>>> FLAG = 100
>>>
>>> class A:
... def func(self):
... return FLAG*10
...
>>> a = A()
>>> dump = dill.dumps(a.func, recurse=True)
>>> del FLAG
>>> foo = dill.loads(dump)
>>> foo()
1000
>>>
dill
提供多种设置,为您提供序列化变体。如果你想一直使用这个设置,那么你可以这样做:
>>> dill.settings['recurse'] = True
这是一个示例代码,其中 FLAG
是一个全局变量。方法 A.func
对我来说是一个黑盒子,所以我不知道它在序列化之前调用 FLAG
。
import dill as pickle
FLAG = 100
class A:
def func(self):
print FLAG * 10
a = A()
dump = pickle.dumps(a.func)
del FLAG
foo = pickle.loads(dump) <-- fail here "NameError: global name 'FLAG' is not defined"
foo()
相关问题:
- Serialize a python function with dependencies
- How to pickle a python function with its dependencies?
最实用的解决方案是使用 cloudpickle
。但是好像dill
比cloudpickle
更健壮。所以我想坚持使用 dill
或其他成熟的 picklers。
如果需要,我不介意自己修改一些 dill
代码。
提前感谢您的帮助:)
我是 dill
作者。如果您使用 recurse
设置,它会起作用,它处理全局变量的方式与 cloudpickle
处理全局变量的方式非常相似。
>>> import dill
>>> FLAG = 100
>>>
>>> class A:
... def func(self):
... return FLAG*10
...
>>> a = A()
>>> dump = dill.dumps(a.func, recurse=True)
>>> del FLAG
>>> foo = dill.loads(dump)
>>> foo()
1000
>>>
dill
提供多种设置,为您提供序列化变体。如果你想一直使用这个设置,那么你可以这样做:
>>> dill.settings['recurse'] = True