gpt4 book ai didi

python - 如何在 pickle 加载期间用 None 替换导致导入错误的对象?

转载 作者:行者123 更新时间:2023-12-05 05:19:02 24 4
gpt4 key购买 nike

我有一个 pickled 结构,由嵌套的内置基元(列表、字典)和不再在项目中的类实例组成,因此在 unpickling 期间会导致错误。我不太关心那些对象,我希望我可以提取存储在这个嵌套结构中的数值。有什么方法可以从文件中解开并替换由于导入问题而损坏的所有内容,比方说,None

我试图从 Unpickler 继承并覆盖 find_class(self, module, name) 以在找不到类时返回 Dummy ,但出于某种原因,之后我在 load reduce 中不断收到 TypeError: 'NoneType' object is not callable

class Dummy(object):
def __init__(self, *argv, **kwargs):
pass

我试过类似的东西

class RobustJoblibUnpickle(Unpickler):
def find_class(self, _module, name):
try:
super(RobustJoblibUnpickle, self).find_class(_module, name)
except ImportError:
return Dummy

最佳答案

也许你可以在 try block 中捕获异常,然后做你想做的事( set some object to None use a Dummy class )?

编辑:

看看这个,我不知道这样做是否正确,但它似乎工作正常:

import sys
import pickle

class Dummy:
pass

class MyUnpickler(pickle._Unpickler):
def find_class(self, module, name): # from the pickle module code but with a try
# Subclasses may override this. # we are doing it right now...
try:
if self.proto < 3 and self.fix_imports:
if (module, name) in _compat_pickle.NAME_MAPPING:
module, name = _compat_pickle.NAME_MAPPING[(module, name)]
elif module in _compat_pickle.IMPORT_MAPPING:
module = _compat_pickle.IMPORT_MAPPING[module]
__import__(module, level=0)
if self.proto >= 4:
return _getattribute(sys.modules[module], name)[0]
else:
return getattr(sys.modules[module], name)
except AttributeError:
return Dummy

# edit: as per Ben suggestion an even simpler subclass can be used
# instead of the above

class MyUnpickler2(pickle._Unpickler):
def find_class(self, module, name):
try:
return super().find_class(module, name)
except AttributeError:
return Dummy

class C:
pass

c1 = C()

with open('data1.dat', 'wb') as f:
pickle.dump(c1,f)

del C # simulate the missing class

with open('data1.dat', 'rb') as f:
unpickler = MyUnpickler(f) # or MyUnpickler2(f)
c1 = unpickler.load()

print(c1) # got a Dummy object because of missing class

关于python - 如何在 pickle 加载期间用 None 替换导致导入错误的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46857615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com