Python Forum

Full Version: List of mixed data types to bytes
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, my question is as follows:
Assume I have a list that contains mixed types. For instance

firstelement = [0,(a,b)]
secondelement = [1,(c,d)]
mylist = [firstelement,secondelement]
where a,b,c,d are some objects

>>> type(a)
<class '__main__.myObject'>
I want to add the elements of mylist into a Merkle Tree. I searched and found the pymerkle library https://pymerkle.readthedocs.io/en/latest/index.html
(maybe there's a better one, if yes please suggest)

However the libarary (as well as another one I've tried) requires the elements stored in the tree to be represented as bytes.
What is the best way to convert each element of mylist to byte representation?
You can standard pickle module, e.g.

import pickle
from io import BytesIO

bs = BytesIO()

class MyClass:
    ...

mm = MyClass()
# lets store mm as a bytestring

pickle.dump(mm, bs)
bs.seek(0) # move to the begining of the File-like object
print(bs.read()) # this bytesting represents the instance of MyClass (mm)

# you can restore the object, e.g.
bb.seek(0)
restored = pickle.load(bs)
If objects are really complex, you could try to customize __setstate__ and __getstate__ methods (see official docs on pickle module for details).