14.1. Serialization About

  • What is serialization?

  • Serialization - convert object to string for save to file or send over network

  • Deserialization - recreating object from string with serialized data

  • Dumps = object -> str (convert object to string)

  • Loads = str -> object (reconstruct object from string)

  • Dump = object -> file (convert object and write result to file)

  • Load = file -> object (reconstruct object from data in file)

Serialization is the process of converting an object into a format that can be easily stored or transmitted and then reconstructed later. This is useful for saving the state of an object to a file, sending it over a network, or storing it in a database. Common serialization formats include JSON, XML, and binary formats like those used by the pickle module in Python.

14.1.1. Dumps

  • object -> string

>>> def dumps(object):
...     return ','.join(data)
>>>
>>>
>>> data = ('Mark', 'Melissa', 'Rick')
>>> dumps(data)
'Mark,Melissa,Rick'

14.1.2. Loads

  • string -> object

>>> def loads(string):
...     return string.split(',')
>>>
>>>
>>> data = 'Mark,Melissa,Rick'
>>> loads(data)
['Mark', 'Melissa', 'Rick']

14.1.3. Dump

  • object -> file

>>> def dump(object, file):
...     result = ','.join(data) + '\n'
...     with open(file, mode='wt') as file:
...         file.write(result)
>>>
>>>
>>> data = ('Mark', 'Melissa', 'Rick')
>>> dump(data, '/tmp/myfile.csv')
$ cat /tmp/myfile.csv
Mark,Melissa,Rick

14.1.4. Load

  • file -> object

$ echo 'Mark,Melissa,Rick' > /tmp/myfile.csv
>>> def load(file):
...     with open(file, mode='rt') as file:
...         data = file.read().strip()
...         return data.split(',')
>>>
>>>
>>> load('/tmp/myfile.csv')
['Mark', 'Melissa', 'Rick']