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. Formats

  • CSV

  • JSON

  • XML

  • YAML

  • Pickle

  • TOML

14.1.2. Naive Example

  • object -> string

  • data = ['Alice', 'Bob', 'Carol']

  • str(object) -> will convert the object to a string representation

  • eval(str) -> will evaluate the string representation and reconstruct the original object

  • Mind, that eval is dangerous and should be avoided in production code, as it can execute arbitrary code.

  • Do not use eval on untrusted input, as it can lead to very serious security vulnerabilities.

>>> data = ['Alice', 'Bob', 'Carol']
>>>
>>> serialized = str(data)
>>> serialized
"['Alice', 'Bob', 'Carol']"
>>>
>>> deserialized = eval(serialized)
>>> deserialized
['Alice', 'Bob', 'Carol']

14.1.3. Dumps

  • object -> string

  • def dumps(obj, /, *, fieldseparator=',')

  • data = ['Alice', 'Bob', 'Carol']

>>> def dumps(obj, /, *, fieldseparator=','):
...     return fieldseparator.join(obj)
>>>
>>>
>>> data = ['Alice', 'Bob', 'Carol']
>>> dumps(data)
'Alice,Bob,Carol'

14.1.4. Loads

  • string -> object

  • def loads(string, /, *, fieldseparator=',')

  • data = 'Alice,Bob,Carol'

>>> def loads(string, /, *, fieldseparator=','):
...     return string.split(fieldseparator)
>>>
>>>
>>> data = 'Alice,Bob,Carol'
>>> loads(data)
['Alice', 'Bob', 'Carol']

14.1.5. Dump

  • object -> file

  • object -> string -> file

  • def dump(obj, filename, /, *, fieldseparator=',', lineterminator='\n', encoding='utf-8')

  • data = ['Alice', 'Bob', 'Carol']

  • dump(data, '/tmp/myfile.dat')

>>> def dump(obj, filename, /, *, fieldseparator=',', lineterminator='\n', encoding='utf-8'):
...     data = fieldseparator.join(obj) + lineterminator
...     with open(filename, mode='wt', encoding=encoding) as file:
...         file.write(data)
>>>
>>>
>>> data = ['Alice', 'Bob', 'Carol']
>>> dump(data, '/tmp/myfile.dat')
$ cat /tmp/myfile.dat
Alice,Bob,Carol

14.1.6. Load

  • file -> object

  • file -> string -> object

  • def load(filename, /, *, fieldseparator=',', lineterminator='\n', encoding='utf-8')

  • load('/tmp/myfile.dat')

$ echo 'Alice,Bob,Carol' > /tmp/myfile.dat
>>> def load(filename, /, *, fieldseparator=',', lineterminator='\n', encoding='utf-8'):
...     with open(filename, mode='rt', encoding=encoding) as file:
...         data = file.read().rstrip(lineterminator)
...         return data.split(fieldseparator)
>>>
>>>
>>> load('/tmp/myfile.dat')
['Alice', 'Bob', 'Carol']

14.1.7. Assignments

# %% About
# - Name: Serialization About Dumps
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define function `dumps()` serializing `list[str]` to `str`:
#    - Argument: `data: list[str]`, `fieldseparator: str = ','`
#    - Returns: `str`
# 2. Join data by field separator `fieldseparator`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `dumps()` serializującą `list[str]` do `str`:
#    - Argument: `data: list[str]`, `fieldseparator: str = ','`
#    - Zwraca: `str`
# 2. Złącz dane separatorem pól `fieldseparator`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> result
# 'Alice,Bob,Carol'

# %% Hints
# - `str.join()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 12), \
'Python has an is invalid version; expected: `3.12` or newer.'

>>> result = dumps(DATA)

>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'

>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'

>>> assert type(result) is str, \
'Variable `result` has an invalid type; expected: `str`.'

>>> result
'Alice,Bob,Carol'
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
dumps: Callable[[list[str], str], str]
result: str

# %% Data
DATA = ['Alice', 'Bob', 'Carol']

# %% Result
def dumps(data, fieldseparator=','):
    ...

# %% About
# - Name: Serialization About Loads
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define function `loads()` deserializing `str` to `list[str]`:
#    - Argument: `data: str`, `fieldseparator: str = ','`
#    - Returns: `list[str]`
# 2. Split data by field separator `fieldseparator`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `loads()` deserializującą `str` do `list[str]`:
#    - Argument: `data: list[str]`, `fieldseparator: str = ','`
#    - Zwraca: `str`
# 2. Rozdziel dane separatorem pól `fieldseparator`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> result
# ['Alice', 'Bob', 'Carol']

# %% Hints
# - `str.split()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 12), \
'Python has an is invalid version; expected: `3.12` or newer.'

>>> result = loads(DATA)

>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'

>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'

>>> assert type(result) is list, \
'Variable `result` has an invalid type; expected: `list`.'

>>> assert all(type(x) is str for x in result), \
'Variable `result` has elements of an invalid type; all items should be: `str`.'

>>> result
['Alice', 'Bob', 'Carol']
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
loads: Callable[[str, str], list[str]]
result: list[str]

# %% Data
DATA = 'Alice,Bob,Carol'

# %% Result
def loads(data, fieldseparator=','):
    ...

# %% About
# - Name: Serialization About Dump
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define function `dump()` serializing `list[str]` to `str` and writing to `FILE`:
#    - Argument: `data: list[str]`, `filename: str`, `fieldseparator: str = ','`
#    - Returns: `None`
# 2. Join data by field separator `fieldseparator`
# 3. Write data to file using `utf-8` encoding
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `dump()` serializującą `list[str]` do `str`:
#    - Argument: `data: list[str]`, `fieldseparator: str = ','`
#    - Zwraca: `str`
# 2. Złącz dane separatorem pól `fieldseparator`
# 3. Zapisz dane do pliku używając kodowania `utf-8`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> print(result)
# None

# %% Hints
# - `str.join()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 12), \
'Python has an is invalid version; expected: `3.12` or newer.'

>>> result = dump(DATA, FILE)

>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'

>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'

>>> assert result is None, \
'Variable `result` has an invalid type; expected: `None`.'

>>> from os import remove
>>> remove(FILE)

>>> print(result)
None
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
dump: Callable[[list[str], str, str], None]
result: str

# %% Data
FILE = '_temporary.dat'
DATA = ['Alice', 'Bob', 'Carol']

# %% Result
def dump(data, filename, fieldseparator=','):
    ...

# %% About
# - Name: Serialization About Loads
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define function `load()` reading data from `FILE` and deserializing `str` to `list[str]`:
#    - Argument: `filename: str`, `fieldseparator: str = ','`
#    - Returns: `list[str]`
# 2. Split data by field separator `fieldseparator`
# 3. Read data from file using `utf-8` encoding
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `load()` deserializującą `str` do `list[str]`:
#    - Argument: `filename: list[str]`, `fieldseparator: str = ','`
#    - Zwraca: `str`
# 2. Rozdziel dane separatorem pól `fieldseparator`
# 3. Odczytaj dane z pliku używając kodowania `utf-8`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> result
# ['Alice', 'Bob', 'Carol']

# %% Hints
# - `str.split()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 12), \
'Python has an is invalid version; expected: `3.12` or newer.'

>>> result = load(FILE)

>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'

>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'

>>> assert type(result) is list, \
'Variable `result` has an invalid type; expected: `list`.'

>>> assert all(type(x) is str for x in result), \
'Variable `result` has elements of an invalid type; all items should be: `str`.'

>>> from os import remove
>>> remove(FILE)

>>> result
['Alice', 'Bob', 'Carol']
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
load: Callable[[str,str], list[str]]
result: list[str]

# %% Data
FILE = '_temporary.dat'

with open(FILE, mode='wt', encoding='utf-8') as file:
    file.write('Alice,Bob,Carol')

# %% Result
def load(filename, fieldseparator=','):
    ...

# %% About
# - Name: Serialization Dump File
# - Difficulty: medium
# - Lines: 12
# - Minutes: 13

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define function `dump()`, which serializes list[Mapping] to file:
#    - Argument: `obj: list[dict]`, `filename: str`, `encoding: str = 'utf-8'`
#    - Returns: `None`
# 2. Non-functional requirements:
#    - Do not use `import` and any module
#    - Do not convert numbers to `int` or `float`, leave them as `str`
#    - Quoting: none
#    - Field Separator: `,`
#    - Record Separator: `;`
#    - File ends with an empty line
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `dump()`, która serializuje list[Mapping] do pliku:
#    - Argument: `obj: list[dict]`, `filename: str`, `encoding: str = 'utf-8'`
#    - Zwraca: `None`
# 2. Wymagania niefunkcjonalne:
#    - Nie używaj `import` ani żadnych modułów
#    - Nie konwertuj liczb do `int` lub `float`, pozostaw je jako `str`
#    - Quoting: żadne
#    - Field Separator: `,`
#    - Record Separator: `;`
#    - Plik kończy się pustą linią
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> result
# age,firstname,lastname;30,Alice,Apricot;31,Bob,Blackthorn;32,Carol,Corn;33,Dave,Durian;34,Eve,Elderberry;15,Mallory,Melon
# <BLANKLINE>

# %% Hints
# - `tuple()`
# - `dict.keys()`
# - `dict.values()`
# - `list.append()`
# - `list.extend()`
# - `str.join()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 12), \
'Python has an is invalid version; expected: `3.12` or newer.'

>>> dump(DATA, FILE)
>>> result = open(FILE).read()

>>> from os import remove
>>> remove(FILE)

>>> assert type(result) is str, \
'Variable `result` has an invalid type; expected: `str`.'

>>> assert result != '', \
'File content is empty'

>>> print(result)
age,firstname,lastname;30,Alice,Apricot;31,Bob,Blackthorn;32,Carol,Corn;33,Dave,Durian;34,Eve,Elderberry;15,Mallory,Melon
<BLANKLINE>
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
type data = list[dict[str,str|int]]
dump: Callable[[data], None]

# %% Data
FILE = '_temporary.csv'

DATA = [
    {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
    {'firstname': 'Bob', 'lastname': 'Blackthorn', 'age': 31},
    {'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
    {'firstname': 'Dave', 'lastname': 'Durian', 'age': 33},
    {'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34},
    {'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15},
]

def dumps(obj, /, *, fieldseparator=',', recordseparator=';'):
    keys = sorted(set(key for row in obj for key in row.keys()))
    values = [[row.get(key,'') for key in keys] for row in obj]
    header = fieldseparator.join(str(x) for x in keys)
    rows = [fieldseparator.join(str(x) for x in row) for row in values]
    result = recordseparator.join([header] + rows)
    return result

# %% Result
def dump(obj, filename, /, *, fieldseparator=',', recordseparator=';', lineterminator='\n', encoding='utf-8'):
    ...

# %% About
# - Name: Serialization Loads ListObject
# - Difficulty: easy
# - Lines: 4
# - Minutes: 5

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define function `load()`, which deserialize from file to list[object]:
#    - Argument: `filename: str`
#    - Returns: `list[dict]`
# 2. Define `result: data: list[dict]` with result of `dumps()` function for `DATA`
# 3. Non-functional requirements:
#    - Do not use `import` and any module
#    - Do not convert numbers to `int` or `float`, leave them as `str`
#    - Quoting: none
#    - Field Separator: `,`
#    - Record Separator: `;`
#    - File ends with an empty line
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `load()`, która deserializuje z pliku do list[object]:
#    - Argument: `filename: str`
#    - Zwraca: `list[dict]`
# 2. Zdefiniuj `result: list[object]` z wynikiem funkcji `dumps()` dla `DATA`
# 3. Wymagania niefunkcjonalne:
#    - Nie używaj `import` ani żadnych modułów
#    - Nie konwertuj liczb do `int` lub `float`, pozostaw je jako `str`
#    - Quoting: żadne
#    - Field Separator: `,`
#    - Record Separator: `;`
#    - Plik kończy się pustą linią
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> result
# [{'age': '30', 'firstname': 'Alice', 'lastname': 'Apricot'},
#  {'age': '31', 'firstname': 'Bob', 'lastname': 'Blackthorn'},
#  {'age': '32', 'firstname': 'Carol', 'lastname': 'Corn'},
#  {'age': '33', 'firstname': 'Dave', 'lastname': 'Durian'},
#  {'age': '34', 'firstname': 'Eve', 'lastname': 'Elderberry'},
#  {'age': '15', 'firstname': 'Mallory', 'lastname': 'Melon'}]

# %% Hints
# - `[x for x in data]`
# - `tuple()`
# - `str.split()`
# - `dict()`
# - `zip()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 12), \
'Python has an is invalid version; expected: `3.12` or newer.'

>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'

>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'

>>> assert type(result) is list, \
'Variable `result` has an invalid type; expected: `list`.'

>>> assert all(type(x) is dict for x in result), \
'Variable `result` has elements of an invalid type; all items should be: `dict`.'

>>> from pprint import pprint
>>> pprint(result, sort_dicts=False, width=79)
[{'age': '30', 'firstname': 'Alice', 'lastname': 'Apricot'},
 {'age': '31', 'firstname': 'Bob', 'lastname': 'Blackthorn'},
 {'age': '32', 'firstname': 'Carol', 'lastname': 'Corn'},
 {'age': '33', 'firstname': 'Dave', 'lastname': 'Durian'},
 {'age': '34', 'firstname': 'Eve', 'lastname': 'Elderberry'},
 {'age': '15', 'firstname': 'Mallory', 'lastname': 'Melon'}]

>>> from os import remove
>>> remove(FILE)
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
type data = list[object]
loads: Callable[[str,...], data]
result: data

# %% Data
DATA = 'age,firstname,lastname;30,Alice,Apricot;31,Bob,Blackthorn;32,Carol,Corn;33,Dave,Durian;34,Eve,Elderberry;15,Mallory,Melon'
FILE = '_temporary.dat'

with open(FILE, mode='wt', encoding='utf-8') as file:
    file.write(DATA)

def loads(string, /, *, fieldseparator=',', recordseparator=';'):
    records = string.split(recordseparator)
    keys, *values = [record.split(fieldseparator) for record in records]
    result = [dict(zip(keys, row)) for row in values]
    return result

# %% Result
def load(filename, /, *, fieldseparator=',', recordseparator=';'):
    ...


result = ...