I have a python class representing grouped Dicom series from a particular subject, defined in a module dicom_parser.py
. When instantiated, the class calls methods which read and sort Dicoms via UID.
import os
import pydicom as pdi
class DicomSeries():
def __init__(self):
self._dcm_unsort_headers = self._dicom_parse("/home/hamilton/dicoms/XYZ_fmri_2011")
self.dcm_grouped = self._dicom_sort(self._dcm_unsort_headers)
delattr(self, "_dcm_unsort_headers")
@staticmethod
def _dicom_parse(dcm_dir):
# Find and parse all, return unsorted list
return dcm_headers
@staticmethod
def _dicom_sort(dcm_headers):
# Sort list of dcm_headers by UID
return dcm_grouped
dicom_parser.py
is imported and called from a main.py
script.
I've written a save and load method, taken from bivouac0's answer on this post. save()
is called via weakref.finalize
, while load()
is called if the saved file is present when __init__()
is called.
import os
import pickle
from weakref import finalize
class DicomSeries():
def __init__(self, filename = 'XYZ_dcms.pkl.gz'):
if os.path.exists(filename) is True
self = self.load()
else:
# Load and sort
self._finalizer = finalize(self, self.save, filename = self.filename)
def save(self, filename = None):
if filename is None:
filename = self.filename
with gzip.open(filename, 'wb') as f:
pickle.dump(self, f, protocol=pickle.HIGHEST_PROTOCOL)
def load(self, filename = None):
if filename is None:
filename = self.filename
with gzip.open(filename, 'rb') as f:
old = pickle.load(f)
return old
The class saves successfully upon deletion or script exit; however if the object is instantiated again in a new script call, the loaded object is void of all attributes declared in the previous instance (e.g. sub.dcm_grouped
is not defined).
How might I go about fixing this and achieving the desired behavior of:
- Save instance on object deletion or script exit (i.e. gc)
- Load instance upon object instantiation if
filename
is present.