12.5. Serialization Recap

# FIXME: Zmienić dane na Userów
# FIXME: Uspójnić zadania z pikle, json, toml
# FIXME: zdefiniuj funkcję load, która czyta z pliku ...

# %% About
# - Name: Serialization Recap String
# - Difficulty: easy
# - Lines: 1
# - Minutes: 3

# %% 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. Convert `DATA` to `result: list[tuple[str]]`
# 2. Do not convert numeric values to `float`, leave them as `str`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Przekonwertuj `DATA` to `result: list[tuple[str]]`
# 2. Nie konwertuj wartości numerycznych do `float`, zostaw jako `str`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> 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')]

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

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> result = list(result)
>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'
>>> assert all(type(x) is tuple for x in result), \
'All rows in `result` should be tuple'

>>> from pprint import pprint
>>> pprint(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')]
"""

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

# %% Imports

# %% Types
result: list[tuple]

# %% Data
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"""

# %% Result
result = ...

# FIXME: Zmienić dane na Userów
# FIXME: Uspójnić zadania z pikle, json, toml
# FIXME: zdefiniuj funkcję load, która czyta z pliku ...

# %% About
# - Name: Serialization Recap TypeCast
# - Difficulty: easy
# - Lines: 9
# - Minutes: 8

# %% 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. Convert `DATA` to `result: list[tuple[str]]`
# 2. Convert numeric values to `float`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Przekonwertuj `DATA` to `result: list[tuple[str]]`
# 2. Przekonwertuj wartości numeryczne do `float`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> 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')]

# %% Hints
# - `a, *b = ...`
# - `str.splitlines()`
# - `str.split()`
# - `dict.get()`
# - `float()`
# - `tuple()`
# - `tuple() + tuple()`
# - `list.append()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> result = list(result)  # expand map object
>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'
>>> assert all(type(x) is tuple for x in result), \
'All rows in `result` should be tuple'

>>> from pprint import pprint
>>> pprint(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')]
"""

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

# %% Imports

# %% Types
result: list[tuple]

# %% Data
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"""

# %% Result
result = ...

# FIXME: Wywalić, funkcja jest zbyt specyficzna tylko dla jednego usecase
# FIXME: Uspójnić zadania z pikle, json, toml
# FIXME: zdefiniuj funkcję load, która czyta z pliku ...

# %% About
# - Name: Serialization Recap Switch
# - Difficulty: easy
# - 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. Convert `DATA` to `result: list[tuple[str]]`
# 2. Convert numeric values to `float`
# 3. Substitute last element (label) with value from `ENCODER`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Przekonwertuj `DATA` to `result: list[tuple[str]]`
# 2. Przekonwertuj wartości numeryczne do `float`
# 3. Podmień ostatni element (etykietę) z wartością z `ENCODER`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> 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')]

# %% Hints
# - `a, *b = ...`
# - `str.splitlines()`
# - `str.split()`
# - `dict.get()`
# - `float()`
# - `tuple()`
# - `tuple() + tuple()`
# - `list.append()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> result = list(result)  # expand map object
>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'
>>> assert all(type(x) is tuple for x in result), \
'All rows in `result` should be tuple'

>>> from pprint import pprint
>>> pprint(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')]
"""

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

# %% Imports

# %% Types
result: list[tuple]

# %% Data
DATA = """sepal_length,sepal_width,petal_length,petal_width,species
5.8,2.7,5.1,1.9,0
5.1,3.5,1.4,0.2,1
5.7,2.8,4.1,1.3,2"""

ENCODER = {
    0: 'virginica',
    1: 'setosa',
    2: 'versicolor',
}

# %% Result
result = ...

# FIXME: Wywalić, funkcja jest zbyt specyficzna tylko dla jednego usecase
# FIXME: Uspójnić zadania z pikle, json, toml
# FIXME: zdefiniuj funkcję load, która czyta z pliku ...

# %% About
# - Name: Serialization Recap Encoder
# - 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. Convert `DATA` to `result: list[tuple[str]]`
# 2. Generate `ENCODER: dict[int,str]` from `header: list[str]`
# 3. Convert numeric values to `float`
# 4. Substitute last element (label) with value from `ENCODER`
# 5. Run doctests - all must succeed

# %% Polish
# 1. Przekonwertuj `DATA` to `result: list[tuple[str]]`
# 2. Wygeneruj `ENCODER: dict[int,str]` z `header: list[str]`
# 3. Przekonwertuj wartości numeryczne do `float`
# 4. Podmień ostatni element (etykietę) z wartością z `ENCODER`
# 5. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# [(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')]

# %% Hints
# - `a, *b = ...`
# - `dict(enumerate())`
# - `str.splitlines()`
# - `str.split()`
# - `dict.get()`
# - `float()`
# - `tuple()`
# - `tuple() + tuple()`
# - `list.append()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> result = list(result)  # expand map object
>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'
>>> assert all(type(x) is tuple for x in result), \
'All rows in `result` should be tuple'

>>> from pprint import pprint
>>> pprint(result)
[(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')]
"""

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

# %% Imports

# %% Types
result: list[tuple]

# %% Data
DATA = """3,4,setosa,virginica,versicolor
5.8,2.7,5.1,1.9,1
5.1,3.5,1.4,0.2,0
5.7,2.8,4.1,1.3,2"""

# %% Result
result = ...

# FIXME: Zmienić dane na Userów
# FIXME: Uspójnić zadania z pikle, json, toml
# FIXME: zdefiniuj funkcję load, która czyta z pliku ...

# %% About
# - Name: Serialization Recap FixedHeader
# - 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. Convert `DATA` to `result: list[dict]`
# 2. Use `HEADER` as dict keys
# 3. Do not convert numeric values to `float`, leave them as `str`
# 4. Run doctests - all must succeed

# %% Polish
# 1. Przekonwertuj `DATA` to `result: list[dict]`
# 2. Użyj `HEADER` jako kluczy dictów
# 3. Nie konwertuj wartości numerycznych do `float`, pozostaw je jako `str`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# [{'petal_length': '5.1',
#   'petal_width': '1.9',
#   'sepal_length': '5.8',
#   'sepal_width': '2.7',
#   'species': 'virginica'},
#  {'petal_length': '1.4',
#   'petal_width': '0.2',
#   'sepal_length': '5.1',
#   'sepal_width': '3.5',
#   'species': 'setosa'},
#  {'petal_length': '4.1',
#   'petal_width': '1.3',
#   'sepal_length': '5.7',
#   'sepal_width': '2.8',
#   'species': 'versicolor'}]

# %% Hints
# - `str.splitlines()`
# - `str.split()`
# - `list.append()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> result = list(result)  # expand map object
>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'
>>> assert all(type(x) is dict for x in result), \
'All rows in `result` should be dict'

>>> from pprint import pprint
>>> pprint(result)
[{'petal_length': '5.1',
  'petal_width': '1.9',
  'sepal_length': '5.8',
  'sepal_width': '2.7',
  'species': 'virginica'},
 {'petal_length': '1.4',
  'petal_width': '0.2',
  'sepal_length': '5.1',
  'sepal_width': '3.5',
  'species': 'setosa'},
 {'petal_length': '4.1',
  'petal_width': '1.3',
  'sepal_length': '5.7',
  'sepal_width': '2.8',
  'species': 'versicolor'}]
"""

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

# %% Imports

# %% Types
result: list[dict[str,str]]

# %% Data
DATA = """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"""

HEADER = [
    'sepal_length',
    'sepal_width',
    'petal_length',
    'petal_width',
    'species',
]

# %% Result
result = ...

# FIXME: Zmienić dane na Userów
# FIXME: Uspójnić zadania z pikle, json, toml
# FIXME: zdefiniuj funkcję load, która czyta z pliku ...

# %% About
# - Name: Serialization Recap GenerateHeader
# - Difficulty: hard
# - Lines: 7
# - Minutes: 8

# %% 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. Generate `header: list[str]` from first line `DATA`
# 2. Convert `DATA` to `result: list[dict]`
# 3. Use `header` as keys
# 4. Convert numeric values to `float`
# 5. Run doctests - all must succeed

# %% Polish
# 1. Wygeneruj `header: list[str]` z pierwszej linii `DATA`
# 2. Przekonwertuj `DATA` to `result: list[dict]`
# 3. Użyj nagłówka jako kluczy
# 4. Przekonwertuj wartości numeryczne do `float`
# 5. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# [{'petal_length': 5.1,
#   'petal_width': 1.9,
#   'sepal_length': 5.8,
#   'sepal_width': 2.7,
#   'species': 'virginica'},
#  {'petal_length': 1.4,
#   'petal_width': 0.2,
#   'sepal_length': 5.1,
#   'sepal_width': 3.5,
#   'species': 'setosa'},
#  {'petal_length': 4.1,
#   'petal_width': 1.3,
#   'sepal_length': 5.7,
#   'sepal_width': 2.8,
#   'species': 'versicolor'}]

# %% Hints
# - `str.split()`
# - `list() + list()`
# - `list.append()`
# - `tuple()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> result = list(result)
>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'
>>> assert all(type(x) is dict for x in result), \
'All rows in `result` should be dict'

>>> from pprint import pprint
>>> pprint(result)
[{'petal_length': 5.1,
  'petal_width': 1.9,
  'sepal_length': 5.8,
  'sepal_width': 2.7,
  'species': 'virginica'},
 {'petal_length': 1.4,
  'petal_width': 0.2,
  'sepal_length': 5.1,
  'sepal_width': 3.5,
  'species': 'setosa'},
 {'petal_length': 4.1,
  'petal_width': 1.3,
  'sepal_length': 5.7,
  'sepal_width': 2.8,
  'species': 'versicolor'}]
"""

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

# %% Imports

# %% Types
result: list[dict]

# %% Data
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"""

# %% Result
result = ...

# %% About
# - Name: Serialization Recap FixedSchema
# - Difficulty: hard
# - Lines: 7
# - 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()`:
#    - Argument: `data: list[dict]`, `file: str`
#    - Returns: `None`
#    - Function writes `data` to `file` in CSV format
#    - Add quote characters to values
#    - Sort header
# 2. Non-functional requirements:
#    - Do not use `import` and any module
#    - Quotechar: `"`
#    - Quoting: always
#    - Delimiter: `,`
#    - Lineseparator: `\n`
#    - Sort `fieldnames`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `dump()`:
#    - Argument: `data: list[dict]`, `file: str`
#    - Zwraca: `None`
#    - Funkcja zapisuje `data` do `file` w formacie CSV
#    - Dodaj znaki cudzysłowu do wartości
#    - Posortuj header
# 2. Wymagania niefunkcjonalne:
#    - Nie używaj `import` ani żadnych modułów
#    - Quotechar: `"`
#    - Quoting: zawsze
#    - Delimiter: `,`
#    - Lineseparator: `\n`
#    - Posortuj `fieldnames`
# 3. Uruchom doctesty - wszystkie muszą się powieść

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

# %% Hints
# - `sorted()`
# - `str.join()`
# - `dict.get(..., default)`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

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

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

>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> assert result != '', \
'File content is empty'

>>> print(result)
"age","firstname","lastname"
"30","Alice","Apricot"
"31","Bob","Banana"
"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 -v myfile.py`

# %% Imports

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

# %% Data
FILE = '_temporary.csv'

DATA = [
    {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
    {'firstname': 'Bob', 'lastname': 'Banana', '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, file):
    ...

# %% About
# - Name: Serialization Recap Schemaless
# - Difficulty: hard
# - Lines: 7
# - 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()`:
#    - Argument: `data: list[dict]`, `file: str`
#    - Returns: `None`
#    - Function writes `data` to `file` in CSV format
#    - Add quote characters to values
#    - Sort header
# 2. Non-functional requirements:
#    - Do not use `import` and any module
#    - Quotechar: `"`
#    - Quoting: always
#    - Delimiter: `,`
#    - Lineseparator: `\n`
#    - Sort `fieldnames`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `dump()`:
#    - Argument: `data: list[dict]`, `file: str`
#    - Zwraca: `None`
#    - Funkcja zapisuje `data` do `file` w formacie CSV
#    - Dodaj znaki cudzysłowu do wartości
#    - Posortuj header
# 2. Wymagania niefunkcjonalne:
#    - Nie używaj `import` ani żadnych modułów
#    - Quotechar: `"`
#    - Quoting: zawsze
#    - Delimiter: `,`
#    - Lineseparator: `\n`
#    - Posortuj `fieldnames`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# "age","firstname","lastname"
# "","Alice","Apricot"
# "31","Bob",""
# "","Carol","Corn"
# "33","","Durian"
# "34","Eve",""
# "15","","Mallory"
# <BLANKLINE>

# %% Hints
# - `sorted()`
# - `set()`
# - `set.update()`
# - `str.join()`
# - `dict.get(..., default)`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

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

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

>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> assert result != '', \
'File content is empty'

>>> print(result)
"age","firstname","lastname"
"","Alice","Apricot"
"31","Bob",""
"","Carol","Corn"
"33","","Durian"
"34","Eve",""
"15","","Mallory"
<BLANKLINE>
"""

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

# %% Imports

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

# %% Data
FILE = '_temporary.csv'

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

# %% Result
def dump(data, file):
    ...

# %% About
# - Name: Serialization Dumps ListObjects
# - Difficulty: medium
# - Lines: 7
# - Minutes: 8

# %% 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. Modify function `dumps()`:
#    - Argument: `data: list[User]`
#    - Returns: `str`
#    - Function converts `data` to CSV format
#    - Add quotes to values
#    - First line is a header
# 2. Define `result: str` with
#    result of `dumps()` function for `DATA`
# 3. Non-functional requirements:
#    - Do not use `import` and any module
#    - Quotechar: `"`
#    - Quoting: all
#    - Delimiter: `,`
#    - Lineseparator: `\n`
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj funkcję `dumps()`:
#    - Argument: `data: list[User]`
#    - Zwraca: `str`
#    - Funkcja konwertuje `data` do formatu CSV
#    - Dodaj cudzysłowie do wartości
#    - Pierwsza linia to nagłówek
# 2. Zdefiniuj `result: str` z
#    wynikiem funkcji `dumps()` dla `DATA`
# 3. Wymagania niefunkcjonalne:
#    - Nie używaj `import` ani żadnych modułów
#    - Quotechar: `"`
#    - Quoting: wszystkie
#    - Delimiter: `,`
#    - Lineseparator: `\n`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# "age","firstname","groups","lastname"
# "30","Alice","[users, staff]","Apricot"
# "31","Bob","[users, staff]","Banana"
# "32","Carol","[users]","Corn"
# "33","Dave","[users]","Durian"
# "34","Eve","[users, staff, admins]","Elderberry"
# "15","Mallory","[]","Melon"
# <BLANKLINE>

# %% 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 3.12+ required'

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'

>>> print(result)
"age","firstname","groups","lastname"
"30","Alice","[users, staff]","Apricot"
"31","Bob","[users, staff]","Banana"
"32","Carol","[users]","Corn"
"33","Dave","[users]","Durian"
"34","Eve","[users, staff, admins]","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 -v myfile.py`

# %% Imports

# %% Types
from typing import Callable
type data = list[User]
dumps: Callable[[data], str]
result: str

# %% Data
class Group:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return f'{self.name}'

class User:
    def __init__(self, firstname, lastname, age=None, groups=None):
        self.firstname = firstname
        self.lastname = lastname
        self.age = age
        self.groups = groups if groups else []

    def __repr__(self):
        clsname = self.__class__.__qualname__
        arguments = ', '.join(f'{k}={v!r}' for k,v in vars(self).items())
        return f'{clsname}({arguments})'

DATA = [
    User(firstname='Alice', lastname='Apricot', age=30, groups=[
        Group('users'),
        Group('staff'),
    ]),

    User(firstname='Bob', lastname='Banana', age=31, groups=[
        Group('users'),
        Group('staff'),
    ]),

    User(firstname='Carol', lastname='Corn', age=32, groups=[
        Group('users'),
    ]),

    User(firstname='Dave', lastname='Durian', age=33, groups=[
        Group('users'),
    ]),

    User(firstname='Eve', lastname='Elderberry', age=34, groups=[
        Group('users'),
        Group('staff'),
        Group('admins'),
    ]),

    User(firstname='Mallory', lastname='Melon', age=15, groups=[]),
]

# %% Result
def dumps(data):
    ...

result = ...