私が尋ねた最初の質問はhow to load a pickle object and resolve certain referencesでした。私が直面している次の問題は、dumps
またはloads
というオブジェクトをバイナリオブジェクトに呼び出すことができないということです。バイナリオブジェクトへのpersistent_idを持つpickleデータ(ダンプとロード)
以下はContextAwarePickler
とContextAwareUnpickler
の実装です。オブジェクトをバイナリ表現に変換したり、変換したりするにはどうすればよいですか?私の知る限り、これはファイルに対してのみ機能します。 load_aware
とdump_aware
:
class ContextawarePickling :
@staticmethod
def load_aware (input_file,context=None) :
return ContextawareUnpickler(input_file).load()
@staticmethod
def dump_aware (object_to_save,output_file):
ContextawarePickler(output_file).dump(object_to_save)
@staticmethod
def loads_aware (stream,context=None) :
file = io.BytesIO(stream)
return ContextawarePickling.load_aware(file)
@staticmethod
def dumps_aware (object_to_save):
f = io.BytesIO()
ContextawarePickling.dump_aware(object_to_save,f)
return f.getvalue()
基本的には最初の2つのユーティリティメソッドを作成します。
import pickle
class ContextAwarePickler(pickle.Pickler):
def persistent_id(self, obj):
# if this is a context, return the key
if isinstance(obj, Context):
return ("Context", context.key)
# pickle as usual
return None
class ContextAwareUnpickler(pickle.Unpickler):
def recover_context(self, key_id):
...
def persistent_load(self, pid):
type_tag, key_id = pid
if type_tag == "Context":
return self.recover_context(key_id)
else:
raise pickle.UnpicklingError("unsupported persistent object")
このコードを共有していただきありがとうございます。私はこれが本当にこれを行うための再掘り起こしの方法だと思う。どうもありがとう。 –