Python Forum
List of mixed data types to bytes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List of mixed data types to bytes
#1
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?
Reply
#2
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).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with to check an Input list data with a data read from an external source sacharyya 3 409 Mar-09-2024, 12:33 PM
Last Post: Pedroski55
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 480 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  What data types can I use for default values? Mark17 1 530 Oct-09-2023, 02:07 PM
Last Post: buran
  In SQL Server, mix data types. shiv11 0 881 Sep-21-2022, 12:50 PM
Last Post: shiv11
  I need to add data types to cython conversion python to c Good_AI_User 1 1,008 Aug-19-2022, 07:52 AM
Last Post: Gribouillis
  Issue in changing data format (2 bytes) into a 16 bit data. GiggsB 11 2,662 Jul-25-2022, 03:19 PM
Last Post: deanhystad
  How to insert different types of data into a function DrData82 0 1,255 Feb-10-2022, 10:41 PM
Last Post: DrData82
  Why changing data in a copied list changes the original list? plumberpy 3 2,234 Aug-14-2021, 02:26 AM
Last Post: plumberpy
  mixed types MattT 2 3,502 Dec-17-2019, 03:44 PM
Last Post: MattT
  understanding output of bytes/raw data rootVIII 3 2,764 Aug-01-2019, 01:00 PM
Last Post: rootVIII

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020