From 28046a19e27acd10c03987c13a1106c5fb68b09c Mon Sep 17 00:00:00 2001 From: Robert Smallshire Date: Sun, 7 Jun 2015 20:12:05 +0200 Subject: [PATCH] Make HeaderPacker pickleable. HeaderPacker requires special pickling support because the standard library Struct object is not pickleable. Instead we pickle the format string extracted from the Struct object when pickling and use it to recreate the Struct object when unpickling. --- segpy/packer.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/segpy/packer.py b/segpy/packer.py index 9de5253..a839d36 100644 --- a/segpy/packer.py +++ b/segpy/packer.py @@ -2,6 +2,7 @@ from collections import OrderedDict from struct import Struct from itertools import zip_longest +from segpy import __version__ from segpy.datatypes import SEG_Y_TYPE_TO_CTYPE from segpy.util import pairwise, intervals_partially_overlap, complementary_intervals @@ -135,6 +136,27 @@ class HeaderPacker: self._structure = structure self._field_name_allocations = field_name_allocations + def __getstate__(self): + + state = self.__dict__.copy() + state['__version__'] = __version__ + state['_structure_format'] = self._structure.format + del state['_structure'] + return state + + def __setstate__(self, state): + if state['__version__'] != __version__: + raise TypeError("Cannot unpickle {} version {} into version {}" + .format(self.__class__.__name__, + state['__version__'], + __version__)) + del state['__version__'] + + structure = Struct(state['_structure_format']) + state['_structure'] = structure + del state['_structure_format'] + self.__dict__.update(state) + @property def header_format_class(self): return self._header_format_class