14.7. Serialization List of Objects
dumps: list[object] -> string
loads: string -> list[object]
14.7.1. Dumps
list[object] -> string
def dumps(obj, /, *, fieldseparator=',', recordseparator=';')dumps(DATA)vars(obj)convertsobjtodict
>>> def dumps(obj, /, *, fieldseparator=',', recordseparator=';'):
... data = [vars(row) for row in obj]
... keys = sorted(set(key for row in data for key in row.keys()))
... values = [[row.get(key,'') for key in keys] for row in data]
... 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
>>>
>>>
>>> class User:
... def __init__(self, firstname, lastname, age):
... self.firstname = firstname
... self.lastname = lastname
... self.age = age
...
... def __repr__(self):
... clsname = self.__class__.__name__
... firstname = self.firstname
... lastname = self.lastname
... age = self.age
... return f'{clsname}({firstname=}, {lastname=}, {age=})'
>>>
>>>
>>> DATA = [
... User('Alice', 'Apricot', age=30),
... User('Bob', 'Blackthorn', age=31),
... User('Carol', 'Corn', age=32),
... User('Dave', 'Durian', age=33),
... User('Eve', 'Elderberry', age=34),
... User('Mallory', 'Melon', age=15),
... ]
>>>
>>> result = dumps(DATA)
>>> result
'age,firstname,lastname;30,Alice,Apricot;31,Bob,Blackthorn;32,Carol,Corn;33,Dave,Durian;34,Eve,Elderberry;15,Mallory,Melon'
14.7.2. Loads
string -> list[object]
def loads(string, /, *, fieldseparator=',', recordseparator=';')loads(DATA)
>>> def loads(string, /, *, fieldseparator=',', recordseparator=';'):
... records = string.split(recordseparator)
... keys, *values = [record.split(fieldseparator) for record in records]
... data = [dict(zip(keys,row)) for row in values]
... result = [User(**row) for row in data]
... return result
>>>
>>>
>>> class User:
... def __init__(self, firstname, lastname, age):
... self.firstname = firstname
... self.lastname = lastname
... self.age = age
...
... def __repr__(self):
... clsname = self.__class__.__name__
... firstname = self.firstname
... lastname = self.lastname
... age = self.age
... return f'{clsname}({firstname=}, {lastname=}, {age=})'
>>>
>>>
>>> DATA = 'age,firstname,lastname;30,Alice,Apricot;31,Bob,Blackthorn;32,Carol,Corn;33,Dave,Durian;34,Eve,Elderberry;15,Mallory,Melon'
>>>
>>> result = loads(DATA)
>>> result
[User(firstname='Alice', lastname='Apricot', age='30'),
User(firstname='Bob', lastname='Blackthorn', age='31'),
User(firstname='Carol', lastname='Corn', age='32'),
User(firstname='Dave', lastname='Durian', age='33'),
User(firstname='Eve', lastname='Elderberry', age='34'),
User(firstname='Mallory', lastname='Melon', age='15')]
14.7.3. Assignments
# %% About
# - Name: Serialization Dumps ListObjects
# - Difficulty: medium
# - Lines: 10
# - 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 `dumps()`, which serializes list[object] to str:
# - Argument: `obj: list[object]`
# - Returns: `str`
# - First line is a header
# - Sort header
# - Mind, that values must be in appropriate columns (according to header)
# 2. Define `result: str` with result of `dumps()` function for `DATA`
# 3. Non-functional requirements:
# - Do not use `import` and any module
# - Quoting: none
# - Field Separator: `,`
# - Record Separator: `;`
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj funkcję `dumps()`, która serializuje list[object] do str:
# - Argument: `obj: list[object]`
# - Zwraca: `str`
# - Pierwsza linia to nagłówek
# - Posortuj nagłówek
# - Zwróć uwagę, aby wartości były w odpowiednich kolumnach (wg. nagłówka)
# 2. Zdefiniuj `result: str` z wynikiem funkcji `dumps()` dla `DATA`
# 3. Wymagania niefunkcjonalne:
# - Nie używaj `import` ani żadnych modułów
# - Quoting: żadne
# - Field Separator: `,`
# - Record Separator: `;`
# 4. 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
# %% Hints
# - `str.join()`
# - `dict.keys()`
# - `dict.values()`
# - `[x for x in data]`
# %% 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 str, \
'Variable `result` has an invalid type; expected: `str`.'
>>> print(result)
age,firstname,lastname;30,Alice,Apricot;31,Bob,Blackthorn;32,Carol,Corn;33,Dave,Durian;34,Eve,Elderberry;15,Mallory,Melon
"""
# %% 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]
dumps: Callable[[data], str]
result: str
# %% Data
class User:
def __init__(self, firstname, lastname, age=None):
self.firstname = firstname
self.lastname = lastname
self.age = age
def __repr__(self):
clsname = self.__class__.__name__
firstname = self.firstname
lastname = self.lastname
age = self.age
return f'{clsname}({firstname=}, {lastname=}, {age=})'
DATA = [
User('Alice', 'Apricot', age=30),
User('Bob', 'Blackthorn', age=31),
User('Carol', 'Corn', age=32),
User('Dave', 'Durian', age=33),
User('Eve', 'Elderberry', age=34),
User('Mallory', 'Melon', age=15),
]
# %% Result
def dumps(obj, /, *, fieldseparator=',', recordseparator=';'):
...
result = ...
# %% About
# - Name: Serialization Loads ListObject
# - Difficulty: easy
# - Lines: 5
# - 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 `loads()`, which deserialize from str to list[object]:
# - Argument: `string: str`
# - Returns: `list[object]`
# 2. Define `result: list[object]` 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: `;`
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj funkcję `loads()`, która deserializuje ze str do list[object]:
# - Argument: `string: str`
# - Zwraca: `list[object]`
# 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: `;`
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> result
# [User(firstname='Alice', lastname='Apricot', age='30'),
# User(firstname='Bob', lastname='Blackthorn', age='31'),
# User(firstname='Carol', lastname='Corn', age='32'),
# User(firstname='Dave', lastname='Durian', age='33'),
# User(firstname='Eve', lastname='Elderberry', age='34'),
# User(firstname='Mallory', lastname='Melon', age='15')]
# %% 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 User for x in result), \
'Variable `result` has elements of an invalid type; all items should be: `User`.'
>>> from pprint import pprint
>>> pprint(result, sort_dicts=False, width=79)
[User(firstname='Alice', lastname='Apricot', age='30'),
User(firstname='Bob', lastname='Blackthorn', age='31'),
User(firstname='Carol', lastname='Corn', age='32'),
User(firstname='Dave', lastname='Durian', age='33'),
User(firstname='Eve', lastname='Elderberry', age='34'),
User(firstname='Mallory', lastname='Melon', age='15')]
"""
# %% 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'
class User:
def __init__(self, firstname, lastname, age):
self.firstname = firstname
self.lastname = lastname
self.age = age
def __repr__(self):
clsname = self.__class__.__name__
firstname = self.firstname
lastname = self.lastname
age = self.age
return f'{clsname}({firstname=}, {lastname=}, {age=})'
# %% Result
def loads(string, /, *, fieldseparator=',', recordseparator=';'):
...
result = ...