Package: hickle
HickleHickle is anHDF5based clone ofpickle, with a twist: instead of serializing to a pickle file,
Hickle dumps to an HDF5 file (Hierarchical Data Format). It is designed to be a "drop-in" replacement for pickle (for common data objects), but is
really an amalgam ofh5pyandpicklewith extended functionality.That is:hickleis a neat little way of dumping python variables to HDF5 files that can be read in most programming
languages, not just Python. Hickle is fast, and allows for transparent compression of your data (LZF / GZIP).Why use Hickle?Whilehickleis designed to be a drop-in replacement forpickle(or something likejson), it works very differently.
Instead of serializing / json-izing, it instead stores the data using the excellenth5pymodule.The main reasons to use hickle are:It's faster than pickle and cPickle.It stores data in HDF5.You can easily compress your data.The main reasons not to use hickle are:You don't want to store your data in HDF5. While hickle can serialize arbitrary python objects, this functionality is provided only for convenience, and you're probably better off just using the pickle module.You want to convert your data in human-readable JSON/YAML, in which case, you should do that instead.So, if you want your data in HDF5, or if your pickling is taking too long, give hickle a try.
Hickle is particularly good at storing large numpy arrays, thanks toh5pyrunning under the hood.DocumentationDocumentation for hickle can be found attelegraphic.github.io/hickle/.Usage exampleHickle is nice and easy to use, and should look very familiar to those of you who have pickled before.In short,hickleprovides two methods: ahickle.loadmethod, for loading hickle files, and ahickle.dumpmethod, for dumping data into HDF5. Here's a complete example:importosimporthickleashklimportnumpyasnp# Create a numpy array of dataarray_obj=np.ones(32768,dtype='float32')# Dump to filehkl.dump(array_obj,'test.hkl',mode='w')# Dump data, with compressionhkl.dump(array_obj,'test_gzip.hkl',mode='w',compression='gzip')# Compare filesizesprint('uncompressed:%ibytes'%os.path.getsize('test.hkl'))print('compressed:%ibytes'%os.path.getsize('test_gzip.hkl'))# Load dataarray_hkl=hkl.load('test_gzip.hkl')# Check the two are the same fileassertarray_hkl.dtype==array_obj.dtypeassertnp.all((array_hkl,array_obj))HDF5 compression optionsA major benefit ofhickleoverpickleis that it allows fancy HDF5 features to
be applied, by passing on keyword arguments on toh5py. So, you can do things like:hkl.dump(array_obj,'test_lzf.hkl',mode='w',compression='lzf',scaleoffset=0,chunks=(100,100),shuffle=True,fletcher32=True)A detailed explanation of these keywords is given athttp://docs.h5py.org/en/latest/high/dataset.html,
but we give a quick rundown below.In HDF5, datasets are stored as B-trees, a tree data structure that has speed benefits over contiguous
blocks of data. In the B-tree, data are split intochunks,
which is leveraged to allowdataset resizingand
compression viafilter pipelines. Filters such asshuffleandscaleoffsetmove your data around to improve compression ratios, andfletcher32computes a checksum.
These file-level options are abstracted away from the data model.Dumping custom objectsHickle provides several options to store objects of custom python classes. Objects of classes derived
from built in classes, numpy, scipy, pandas and astropy objects will be stored using the corresponding
loader provided by hickle. Any other classes per default will be stored as binary pickle string.
Starting with version 4.x hickle offers the possibility to define dedicated loader functions for custom
classes and starting with hickle 5.x these can be collected in module, package and application specific
loader modules.class MyClass():
    def __init__(self):
        self.name = 'MyClass'
        self.value = 42To create a loader forMyClassthecreate_MyClass_datasetand either theload_MyClassor theMyClassContainerclass have to be defined.import hdf5
form hickle.helpters import no_compression


def create_MyClass_dataset(py_obj, h_group, name, **kwargs):
    """ 
    py_obj ..... the instance of MyClass to be dumped
    h_group .... the h5py.Group py_obj should be dumped into
    name ....... the name of the h5py.Dataset or h5py.Group representing py_obj
    **kwargs ... the compression keyword arguments passed to hickle.dump

    # if content of MyClass can be represented as single matrix, vector or scalar
    # values than created a dataset of appropriate size. and either set its shape and 
    # dtype parameters # to the appropriate size and tyoe . or directly pass the data
    # using the data parameter
    ds = h_group.create_dataset(name,data = py_obj.value,**kwargs)

	## NOTE: if your class represents a scalar using empty tuple for shape
    ##       than kwargs have to be filtered by no_compression
    # ds = h_group.create_dataset(name,data = py_obj.value,shape=(),**no_compression(kwargs))

	# set additional attributes providing additional specialisation of content
    ds.attrs['name'] = py_obj.name

    # when done return the new dataset object and an empty tuple or list
    return ds,()

def load_Myclass(h_node, base_type, py_obj_type):
    """
    h_node ........ the h5py.Dataset object containing the data of MyClass object to restore
    base_type ..... byte string naming the loader to be used for restoring MyClass object
    py_obj_type ... MyClass class or MyClass subclass object 
    """

    # py_obj_type should point to MyClass or any of its subclasses
    new_instance = py_obj_type()
    new_instance.name = h_node.attrs['name']
    new_instance.value = h_node[()]
    return new_instanceFor dumping content of complex objects consisting of multiple sub-items which have to be
stored as individual h5py.Dataset or h5py.Group objects than definecreate_MyClass_datasetusingcreate_groupmethod instead ofcreate_datasetand define the correspondingMyClassContainerclass.import h5py
from hickle.helpers import PyContainer

def create_MyClass_dataset(py_obj, h_group, name, **kwargs):
    """ 
    py_obj ..... the instance of MyClass to be dumped
    h_group .... the h5py.Group py_obj should be dumped into
    name ....... the name of the h5py.Dataset or h5py.Group representing py_obj
    **kwargs ... the compression keyword arguments passed to hickle.dump

    ds = h_group.create_group(name)

	# set additional attributes providing additional specialisation of content
    ds.attrs['name'] = py_obj.name

    # when done return the new dataset object and a tuple, list or generator function
	# providing for all subitems a tuple or list describing containgin 
    #  name ..... the name to be used storing the subitem within the h5py.Group object
    #  item ..... the subitem object to be stored
    #  attrs .... dictionary included in attrs of created h5py.Group or h5py.Dataset
    #  kwargs ... the kwargs as passed to create_MyClass_dataset function
    return ds,(('name',py_obj.name,{},kwargs),('value',py_obj.value,{'the answer':True},kwargs))



class MyClassContainer(PyContainer):
    """
    Valid container classes must be derived from hickle.helpers.PyContainer class
    """

    def __init__(self,h5_attrs,base_type,object_type):
		"""
		h5_attrs ...... the attrs dictionary attached to the group representing MyClass
    	base_type ..... byte string naming the loader to be used for restoring MyClass object
    	py_obj_type ... MyClass class or MyClass subclass object 
		"""

		# the optional protected _content parameter of the PyContainer __init__
        # method can be used to change the data structure used to store
        # the subitems passed to the append method of the PyContainer class
        # per default it is set to []
        super().__init__(h5_attrs,base_type,object_type,_content = dict())

	def filter(self,h_parent): # optional overload
        """
		generator member functoin which can be overloaded to reorganize subitems
        of h_parent h5py.Group before being restored by hickle. Its default
        implementation simply yields from h_parent.items(). 
		"""
		yield from super().filter(h_parent)

	def append(self,name,item,h5_attrs): # optional overload
        """
		in case _content parameter was explicitly set or subitems should be sored 
        in specific order or have to be preprocessed before the next item is appended
        than this can be done before storing in self._content.

        name ....... the name identifying subitem item within the parent hdf5.Group
        item ....... the object representing the subitem
        h5_attrs ... attrs dictionary attached to h5py.Dataset, h5py.Group representing item
		"""
		self._content[name] = item

	def convert(self):
        """
		called by hickle when all sub items have been appended to MyClass PyContainer
		this method must be implemented by MyClass PyContainer.
		"""

    	# py_obj_type should point to MyClass or any of its subclasses
    	new_instance = py_obj_type()
		new_instance.__dict__.update(self._content)
		return new_instanceIn a last step the loader for MyClass has to be registered with hickle. This is done by callinghickle.lookup.LoaderManager.register_classmethodfrom hickle.lookup import LoaderManager

# to register loader for object mapped to h5py.Dataset use
LoaderManager.register_class(
   MyClass,                # MyClass type object this loader handles
   b'MyClass',             # byte string representing the name of the loader 
   create_MyClass_Dataset, # the create dataset function defined in first example above
   load_MyClass,           # the load dataset function defined in first example above
   None,                   # usually None
   True,                   # Set to False to force explicit storage of MyClass instances in any case 
   'custom'                # Loader is only used when custom loaders are enabled on calling hickle.dump
)

# to register loader for object mapped to h5py.Group use
LoaderManager.register_class(
   MyClass,                # MyClass type object this loader handles
   b'MyClass',             # byte string representing the name of the loader 
   create_MyClass_Dataset, # the create dataset function defined in first example above
   None,                   # usually None
   MyClassContainer        # the PyContainer to be used to restore content of MyClass
   True,                   # Set to False to force explicit storage of MyClass instances in any case 
   None                    # if set to None loader is enabled unconditionally
)

# NOTE: in case content of MyClass instances may be mapped to h5py.Dataset or h5py.Group dependent upon
# their actual complexity than both types of loaders can be merged into one single
# using one common create_MyClass_dataset functoin and defining load_MyClass function and
# MyClassContainer classFor complex python modules, packages and applications defining several classes to be dumped and handled by
hickle callinghickle.lookup.LoaderManager.register_classexplicitly very quickly becomes tedious and
confusing. Therefore hickle offers from hickle 5.x on the possibility to collect all loaders for classes
and objects defined by your module, package or application within dedicated loader modules and install
them along with your module, package and application.For packages and application packages theload_MyPackage.pyloader module has to be stored withinhickle_loadersdirectory of the package directory (the first which contains ainit.py file) and
should be structured as follows.from hickle.helpers import PyContainer

## define below all create_MyClass_dataset load_MyClass functions and MyClassContainer classes
## of the loaders serving your module, package, application package or application

....

## the class_register table and the exclude_register table are required
## by hickle to properly load and apply your loaders
## each row in the class register table will corresponds to the parameters
## of LoaderManager.register_class and has to be specified in the same order
## as above

class_register = [
   [ MyClass,                # MyClass type object this loader handles
     b'MyClass',             # byte string representing the name of the loader 
     create_MyClass_Dataset, # the create dataset function defined in first example above
     load_MyClass,           # the load dataset function defined in first example above
     None,                   # usually None
     True,                   # Set to False to force explicit storage of MyClass instances in any case 
     'custom'                # Loader is only used when custom loaders are enabled on calling hickle.dump
   ],
   [ MyClass,                # MyClass type object this loader handles
     b'MyClass',             # byte string representing the name of the loader 
     create_MyClass_Dataset, # the create dataset function defined in first example above
     None,                   # usually None
     MyClassContainer        # the PyContainer to be used to restore content of MyClass
     True,                   # Set to False to force explicit storage of MyClass instances in any case 
     None                    # if set to None loader is enabled unconditionally
   ]
]

# used by hickle 4.x legacy loaders and other special loaders
# usually an empty list
exclude_register = []For single file modules and application scripts theload_MyModule.pyorload_MyApp.pyfiles have to
be stored within thehickle_loadersdirectory located within the same directory asMyModule.pyorMy_App.py. For further examples of more complex loaders and on how to store bytearrays and strings
such that they can be compressed when stored see default loader modules inhickle/loaders/directory.Note: storing complex objects in HDF5 fileThe HDF5 file format is designed to store several big matrices, images and vectors efficiently
and attach some metadata and to provide a convenient way access the data through a tree structure.
It is not designed like python pickle format for efficiently mapping the in memory object structure
to a file. Therefore mindlessly storing plenty of tiny objects and scalar values without combining
them into a single datataset will cause the HDF5 and thus the file created by hickle explode. File
sizes of several 10 GB are likely and possible when a pickle file would just need some 100 MB.
This can be prevented bycreate_MyClass_datasetmethod combining sub-items into bigger numpy arrays
or other data structures which can be mapped toh5py.Datasetsandload_MyClassfunction and /orMyClassContainer.convertmethod restoring actual structure of the sub-items on load.Recent changesDecember 2021: Release of version 5, support for h5py >= 3.0 and numpy >= 1.21June 2020: Major refactor to version 4, and removal of support for Python 2.December 2018: Accepted to Journal of Open-Source Software (JOSS).June 2018: Major refactor and support for Python 3.Aug 2016: Added support for scipy sparse matricesbsr_matrix,csr_matrixandcsc_matrix.Performance comparisonHickle runs a lot faster than pickle with its default settings, and a little faster than pickle withprotocol=2set:In[1]:importnumpyasnpIn[2]:x=np.random.random((2000,2000))In[3]:importpickleIn[4]:f=open('foo.pkl','w')In[5]:%timepickle.dump(x,f)# slow by defaultCPUtimes:user2s,sys:274ms,total:2.27sWalltime:2.74sIn[6]:f=open('foo.pkl','w')In[7]:%timepickle.dump(x,f,protocol=2)# actually very fastCPUtimes:user18.8ms,sys:36ms,total:54.8msWalltime:55.6msIn[8]:importhickleIn[9]:f=open('foo.hkl','w')In[10]:%timehickle.dump(x,f)# a bit fasterdumping<type'numpy.ndarray'>tofile<HDF5file"foo.hkl"(moder+)>CPUtimes:user764us,sys:35.6ms,total:36.4msWalltime:36.2msSo if you do continue to use pickle, add theprotocol=2keyword (thanks @mrocklin for pointing this out).For storing python dictionaries of lists, hickle beats the python json encoder, but is slower than uJson. For a dictionary with 64 entries, each containing a 4096 length list of random numbers, the times are:json took 2633.263 ms
uJson took 138.482 ms
hickle took 232.181 msIt should be noted that these comparisons are of course not fair: storing in HDF5 will not help you convert something into JSON, nor will it help you serialize a string. But for quick storage of the contents of a python variable, it's a pretty good option.Installation guidelinesEasy methodInstall withpipby runningpip install hicklefrom the command line.Install on Windows 32 bitPrebuilt Python wheels packages are available on PyPi until H5PY version 2.10 and Python 3.8.
Any newer versions have to be built and installed Manually.Install h5py 2.10 withpipby runningpip install "h5py==2.10"from the commandlineInstall withpipby runningpip install hickleform the command lineManual installYou should have Python 3.5 and above installedInstall hdf5
(Official page:http://www.hdfgroup.org/ftp/HDF5/current/src/unpacked/release_docs/INSTALL)
(Binary Downloads:https://portal.hdfgroup.org/display/support/Downloads)Note:On Windows 32 bit install prebuilt binary package for libhdf51.10.4, which is the latest version supporting 32 bit on WindowsInstall h5py
(Official page:http://docs.h5py.org/en/latest/build.html)Downloadhickle:
via terminal: git clonehttps://github.com/telegraphic/hickle.gitvia manual download: Go tohttps://github.com/telegraphic/hickleand on right hand side you will findDownload ZIPfilecd to your downloadedhickledirectoryThen run the following command in thehickledirectory:python setup.py installOptional requirements:dill: needed when files generated by hickle 3 and/or hickle 4 are to be loaded with hickle >= 5, for developent and testingastropy: needed for development and testingpandas: needed for development and testingTestingOnce installed from source, runpython setup.py testto check it's all working.Bugs & contributingContributions and bugfixes are very welcome. Please check out ourcontribution guidelinesfor more details on how to contribute to development.Referencing hickleIf you usehicklein academic research, we would be grateful if you could referenceour paperin theJournal of Open-Source Software (JOSS).Price et al., (2018). Hickle: A HDF5-based python pickle replacement. Journal of Open Source Software, 3(32), 1115, https://doi.org/10.21105/joss.01115