12.7. 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ść

# %% 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ść

# %% 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. Substitute last element (label) with value from `ENCODER`
# 3. Run doctests - all must succeed

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

# %% Hints
# - `str.splitlines()`
# - `str.split()`
# - `dict.get()`
# - `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. Substitute last element (label) with value from `ENCODER`
# 4. 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. Podmień ostatni element (etykietę) z wartością z `ENCODER`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `a, *b = ...`
# - `dict(enumerate())`
# - `str.splitlines()`
# - `str.split()`
# - `dict.get()`
# - `int()`
# - `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 numerycznychh do `float`, pozostaw je jako `str`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% 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ść

# %% 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[tuple]`, `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[tuple]`, `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ść

# %% 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"
"41","Mark","Watney"
"40","Melissa","Lewis"
"39","Rick","Martinez"
"40","Alex","Vogel"
"36","Chris","Beck"
"29","Beth","Johanssen"
<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': 'Mark', 'lastname': 'Watney', 'age': 41},
    {'firstname': 'Melissa', 'lastname': 'Lewis', 'age': 40},
    {'firstname': 'Rick', 'lastname': 'Martinez', 'age': 39},
    {'firstname': 'Alex', 'lastname': 'Vogel', 'age': 40},
    {'firstname': 'Chris', 'lastname': 'Beck', 'age': 36},
    {'firstname': 'Beth', 'lastname': 'Johanssen', 'age': 29},
]

# %% 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[tuple]`, `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[tuple]`, `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ść

# %% 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"
"","Mark","Watney"
"","Melissa","Lewis"
"39","Rick",""
"40","Alex",""
"36","","Beck"
"29","","Johanssen"
<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': 'Mark', 'lastname': 'Watney'},
    {'firstname': 'Melissa', 'lastname': 'Lewis'},
    {'firstname': 'Rick', 'age': 39},
    {'firstname': 'Alex', 'age': 40},
    {'lastname': 'Beck', 'age': 36},
    {'lastname': 'Johanssen', 'age': 29},
]

# %% 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ść

# %% 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)
"firstname","lastname","age","groups"
"Mark","Watney","41","[Group(users)]"
"Melissa","Lewis","40","[Group(users), Group(staff), Group(admins)]"
"Rick","Martinez","39","[Group(users)]"
"Alex","Vogel","40","[]"
"Beth","Johanssen","29","[Group(users), Group(staff)]"
"Chris","Beck","36","[Group(users)]"
"""

# %% 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):
        clsname = self.__class__.__name__
        return f'{clsname}({self.name})'

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

    def __repr__(self):
        clsname = self.__class__.__name__
        firstname = self.firstname
        lastname = self.lastname
        groups = ','.join(str(x) for x in self.groups)
        age = self.age
        return f'{clsname}({firstname=}, {lastname=}, {age=}, {groups=})'


DATA = [
    User(firstname='Mark', lastname='Watney', age=41, groups=[
        Group('users'),
    ]),

    User(firstname='Melissa', lastname='Lewis', age=40, groups=[
        Group('users'),
        Group('staff'),
        Group('admins'),
    ]),

    User(firstname='Rick', lastname='Martinez', age=39, groups=[
        Group('users'),
    ]),

    User(firstname='Alex', lastname='Vogel', age=40, groups=[]),

    User(firstname='Beth', lastname='Johanssen', age=29, groups=[
        Group('users'),
        Group('staff'),
    ]),

    User(firstname='Chris', lastname='Beck', age=36, groups=[
        Group('users'),
    ]),
]

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

result = ...