11.2. Serialization Dump — Python
dumps(object) -> strdump(object) -> file
11.2.1. Sequence
tuple -> string
def dumps(data, fieldseparator=',')dumps(DATA)
>>> DATA = ('Alice', 'Apricot', 30) >>> >>> def dumps(data, fieldseparator=','): ... fields = [str(field) for field in data] ... return fieldseparator.join(fields) >>> >>> dumps(DATA) 'Alice,Apricot,30'
11.2.2. List of Sequences
list[tuple] -> string
def dumps(obj, fieldseparator=',', recordseparator=';')dumps(DATA)
>>> DATA = [ ... ('firstname', 'lastname', 'age'), ... ('Alice', 'Apricot', 30), ... ('Bob', 'Blackthorn', 31), ... ('Carol', 'Corn', 32), ... ('Dave', 'Durian', 33), ... ('Eve', 'Elderberry', 34), ... ('Mallory', 'Melon', 15), ... ] >>> >>> def dumps(data, fieldseparator=',', recordseparator=';'): ... fields = [[str(field) for field in row] for row in data] ... records = [fieldseparator.join(x) for x in fields] ... return recordseparator.join(records) >>> >>> dumps(DATA) 'firstname,lastname,age;Alice,Apricot,30;Bob,Blackthorn,31;Carol,Corn,32;Dave,Durian,33;Eve,Elderberry,34;Mallory,Melon,15'
11.2.3. Mapping
dict -> string
def dumps(data, fieldseparator=',', recordseparator=';')dumps(DATA)
>>> DATA = {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30} >>> >>> def dumps(data, fieldseparator=',', recordseparator=';'): ... header = [fieldseparator.join(str(x) for x in data.keys())] ... row = [fieldseparator.join(str(x) for x in data.values())] ... return recordseparator.join(header + row) >>> >>> dumps(DATA) 'firstname,lastname,age;Alice,Apricot,30'
11.2.4. List of Mappings
list[dict] -> string
def dumps(data, fieldseparator=',', recordseparator=';')dumps(DATA)
>>> 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(data, fieldseparator=',', recordseparator=';'): ... keys = sorted(set(str(key) for row in data for key in row.keys())) ... values = [[str(row.get(key,'')) for key in keys] for row in data] ... header = [fieldseparator.join(keys)] ... rows = [fieldseparator.join(row) for row in values] ... return recordseparator.join(header + rows) >>> >>> dumps(DATA) 'age,firstname,lastname;30,Alice,Apricot;31,Bob,Blackthorn;32,Carol,Corn;33,Dave,Durian;34,Eve,Elderberry;15,Mallory,Melon'
11.2.5. List of Objects
list[object] -> string
def dumps(data, fieldseparator=',', recordseparator=';')dumps(DATA)vars(obj)convertsobjtodict
>>> 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), ... ] >>> >>> def dumps(data, fieldseparator=',', recordseparator=';'): ... data = [vars(row) for row in data] ... keys = sorted(set(str(key) for row in data for key in row.keys())) ... values = [[str(row.get(key,'')) for key in keys] for row in data] ... header = [fieldseparator.join(keys)] ... rows = [fieldseparator.join(row) for row in values] ... return recordseparator.join(header + rows) >>> >>> dumps(DATA) 'age,firstname,lastname;30,Alice,Apricot;31,Bob,Blackthorn;32,Carol,Corn;33,Dave,Durian;34,Eve,Elderberry;15,Mallory,Melon'
11.2.6. To File
object -> file
def dump(data, filename, fieldseparator=',', recordseparator=';', lineterminator='\n', encoding='utf-8')dump(DATA, '/tmp/myfile.dat')
SetUp:
>>> 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(data, fieldseparator=',', recordseparator=';'): ... keys = sorted(set(str(key) for row in data for key in row.keys())) ... values = [[str(row.get(key,'')) for key in keys] for row in data] ... header = [fieldseparator.join(keys)] ... rows = [fieldseparator.join(row) for row in values] ... return recordseparator.join(header + rows) >>> >>> >>> def dump(data, filename, fieldseparator=',', recordseparator=';', lineterminator='\n', encoding='utf-8'): ... result = dumps(data, fieldseparator, recordseparator) ... with open(filename, mode='wt', encoding=encoding) as file: ... file.write(result + lineterminator) >>> >>> >>> dump(DATA, '/tmp/myfile.dat')
Result:
>>> open('/tmp/myfile.dat').read() 'age,firstname,lastname;30,Alice,Apricot;31,Bob,Blackthorn;32,Carol,Corn;33,Dave,Durian;34,Eve,Elderberry;15,Mallory,Melon\n'
11.2.7. Recap
dumps(object) -> strdump(object) -> file
11.2.8. Use Case - 1
SetUp:
>>> DATA = [ ... ('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'), ... (5.8, 2.7, 5.1, 1.9, 'virginica'), ... (5.1, 3.5, 1.4, 0.2, 'setosa'), ... (5.7, 2.8, 4.1, 1.3, 'versicolor'), ... (6.3, 2.9, 5.6, 1.8, 'virginica'), ... (6.4, 3.2, 4.5, 1.5, 'versicolor'), ... (4.7, 3.2, 1.3, 0.2, 'setosa'), ... (7.0, 3.2, 4.7, 1.4, 'versicolor'), ... (7.6, 3.0, 6.6, 2.1, 'virginica'), ... (4.6, 3.1, 1.5, 0.2, 'setosa'), ... ]
Usage:
>>> def dumps(data, fieldseparator=',', recordseparator=';'): ... header = tuple(DATA[0]) ... rows = tuple(DATA[1:]) ... records = [] ... records.append(fieldseparator.join(str(x) for x in header)) ... records.extend(fieldseparator.join(str(x) for x in row) for row in rows) ... return recordseparator.join(records) >>> >>> >>> dumps(DATA) 'sepal_length,sepal_width,petal_length,petal_width,species;5.8,2.7,5.1,1.9,virginica;5.1,3.5,1.4,0.2,setosa;5.7,2.8,4.1,1.3,versicolor;6.3,2.9,5.6,1.8,virginica;6.4,3.2,4.5,1.5,versicolor;4.7,3.2,1.3,0.2,setosa;7.0,3.2,4.7,1.4,versicolor;7.6,3.0,6.6,2.1,virginica;4.6,3.1,1.5,0.2,setosa'
11.2.9. Use Case - 2
SetUp:
>>> from pprint import pprint >>> >>> class User: ... def __init__(self, firstname, lastname): ... self.firstname = firstname ... self.lastname = lastname >>> >>> DATA = User('Alice', 'Apricot')
Usage:
>>> def dumps(data): ... values = vars(data).values() ... result = ','.join(values) + '\n' ... return result >>> >>> result = dumps(DATA) >>> >>> pprint(result) 'Alice,Apricot\n'
11.2.10. Use Case - 3
>>> from pprint import pprint >>> >>> class User: ... def __init__(self, firstname, lastname): ... self.firstname = firstname ... self.lastname = lastname >>> >>> DATA = [ ... User('Alice', 'Apricot'), ... User('Bob', 'Blackthorn'), ... User('Carol', 'Corn'), ... ]
Usage:
>>> def dumps(data): ... values = [','.join(vars(row).values()) for row in data] ... result = '\n'.join(values) + '\n' ... return result >>> >>> result = dumps(DATA) >>> >>> pprint(result) 'Alice,Apricot\nBob,Blackthorn\nCarol,Corn\n'
11.2.11. Use Case - 4
SetUp:
>>> DATA = [ ... ('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'), ... (5.8, 2.7, 5.1, 1.9, 'virginica'), ... (5.1, 3.5, 1.4, 0.2, 'setosa'), ... (5.7, 2.8, 4.1, 1.3, 'versicolor'), ... (6.3, 2.9, 5.6, 1.8, 'virginica'), ... (6.4, 3.2, 4.5, 1.5, 'versicolor'), ... (4.7, 3.2, 1.3, 0.2, 'setosa'), ... (7.0, 3.2, 4.7, 1.4, 'versicolor'), ... (7.6, 3.0, 6.6, 2.1, 'virginica'), ... (4.6, 3.1, 1.5, 0.2, 'setosa'), ... ]
Solution:
>>> def dump(data, file): ... values = [','.join(map(str, row)) for row in data] ... result = '\n'.join(values) + '\n' ... with open(file, mode='wt') as file: ... file.write(result) >>> >>> dump(DATA, file='/tmp/myfile.csv')
Result:
>>> result = open('/tmp/myfile.csv').read() >>> print(result) sepal_length,sepal_width,petal_length,petal_width,species 5.8,2.7,5.1,1.9,virginica 5.1,3.5,1.4,0.2,setosa 5.7,2.8,4.1,1.3,versicolor 6.3,2.9,5.6,1.8,virginica 6.4,3.2,4.5,1.5,versicolor 4.7,3.2,1.3,0.2,setosa 7.0,3.2,4.7,1.4,versicolor 7.6,3.0,6.6,2.1,virginica 4.6,3.1,1.5,0.2,setosa
11.2.12. Assignments
# %% About # - Name: Serialization Dumps Sequence # - 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 `dumps()`, which serializes Sequence: # - Argument: `data: tuple` # - Returns: `str` # 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 Sequence: # - Argument: `data: tuple` # - Zwraca: `str` # 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 # Alice,Apricot,30 # %% Hints # - `[x for x in data]` # - `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.' >>> 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) Alice,Apricot,30 """ # %% 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 = tuple[str,str,int] dumps: Callable[[data], str] result: str # %% Data DATA = ('Alice', 'Apricot', 30) # %% Result def dumps(data, fieldseparator=','): ... result = ...
# %% About # - Name: Serialization Dumps ListSequence # - Difficulty: medium # - Lines: 6 # - 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 `dumps()`, which serializes list[Sequence]: # - Argument: `data: list[tuple]` # - Returns: `str` # 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[Sequence]: # - Argument: `data: list[tuple]` # - Zwraca: `str` # 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 # firstname,lastname,age;Alice,Apricot,30;Bob,Blackthorn,31;Carol,Corn,32;Dave,Durian,33;Eve,Elderberry,34;Mallory,Melon,15 # %% Hints # - `[x for x in data]` # - `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.' >>> 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) firstname,lastname,age;Alice,Apricot,30;Bob,Blackthorn,31;Carol,Corn,32;Dave,Durian,33;Eve,Elderberry,34;Mallory,Melon,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[tuple[str,str,int]] dumps: Callable[[data], str] result: str # %% Data DATA = [ ('firstname', 'lastname', 'age'), ('Alice', 'Apricot', 30), ('Bob', 'Blackthorn', 31), ('Carol', 'Corn', 32), ('Dave', 'Durian', 33), ('Eve', 'Elderberry', 34), ('Mallory', 'Melon', 15), ] # %% Result def dumps(data, fieldseparator=',', recordseparator=';'): ... result = ...
# %% About # - Name: Serialization Dumps Mapping # - Difficulty: easy # - Lines: 10 # - 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 `dumps()`, which serializes Mapping: # - Argument: `data: dict` # - Returns: `str` # 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 Mapping: # - Argument: `data: dict` # - Zwraca: `str` # 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 # firstname,lastname,age;Alice,Apricot,30 # %% Hints # - `[x for x in data]` # - `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.' >>> 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) firstname,lastname,age;Alice,Apricot,30 """ # %% 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 = dict[str,str|int] dumps: Callable[[data], str] result: str # %% Data DATA = {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30} # %% Result def dumps(data, fieldseparator=',', recordseparator=';'): ... result = ...
# %% About # - Name: Serialization Dumps ListMapping # - 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[Mapping]: # - Argument: `data: list[dict]` # - 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[Mapping]: # - Argument: `data: list[dict]` # - 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[dict[str,str|int]] dumps: Callable[[data], str] result: str # %% Data 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}, ] # %% Result def dumps(data, fieldseparator=',', recordseparator=';'): ... result = ...
# %% 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]: # - Argument: `data: 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]: # - Argument: `data: 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(data, fieldseparator=',', recordseparator=';'): ... result = ...
# %% 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[dict] to file: # - Argument: `data: 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[dict] do pliku: # - Argument: `data: 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}, ] # %% Result def dump(data, filename, encoding='utf-8'): ...