19.3. Dataclass Relations

19.3.1. SetUp

>>> from dataclasses import dataclass
>>> from typing import Self

19.3.2. Composition

>>> @dataclass
... class Group:
...     gid: int
...     name: str
>>>
>>>
>>> @dataclass
... class User:
...     firstname: str
...     lastname: str
...     group: Group

Usage:

>>> mark = User('Alice', 'Apricot', group=Group(gid=1, name='users'))

19.3.3. Aggregation

>>> @dataclass
... class Group:
...     gid: int
...     name: str
>>>
>>>
>>> @dataclass
... class User:
...     firstname: str
...     lastname: str
...     groups: list[Group]

Usage:

>>> mark = User('Alice', 'Apricot', groups=[
...     Group(gid=1, name='users'),
...     Group(gid=2, name='staff'),
...     Group(gid=3, name='admins'),
... ])

19.3.4. Forward Reference

>>> @dataclass
... class User:
...     firstname: str
...     lastname: str
...     friends: list[Self] | None = None

Usage:

>>> alice = User('Alice', 'Apricot', friends=[
...     User('Bob', 'Blackthorn'),
...     User('Carol', 'Corn'),
...     User('Dave', 'Durian'),
...     User('Eve', 'Elderberry'),
...     User('Mallory', 'Melon'),
... ])

19.3.5. Assignments

# %% About
# - Name: Dataclass Relations Composition
# - Difficulty: easy
# - Lines: 1
# - Minutes: 1

# %% 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 the `User` dataclass to have an additional attribute `group`
# 2. Use composition
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj dataclass `User`, aby miał dodatkowy atrybut `group`
# 2. Użyj kompozycji
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# @dataclass
# class User:
#     firstname: str
#     lastname: str
#     group: ...

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

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

>>> from inspect import isclass

>>> assert isclass(User), \
'Object `User` has an invalid type; expected: `class`.'

>>> result = User('Alice', 'Apricot', group=Group(gid=1, name='users'))
>>>
>>> assert type(result) is User, \
'Result has an invalid type; expected: `User`.'

>>> assert hasattr(result, 'group'), \
'Result has an invalid attribute; expected: to have an attribute `group`.'

>>> assert type(result.group) is Group, \
'Result has an invalid attribute; expected: `group` to be of type `Group`.'
"""

# %% 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
from dataclasses import dataclass

# %% Types
User: type
Group: type

# %% Data
@dataclass
class Group:
    gid: int
    name: str

# %% Result
@dataclass
class User:
    firstname: str
    lastname: str

# %% About
# - Name: Dataclass Relations Aggregation
# - Difficulty: easy
# - Lines: 1
# - Minutes: 1

# %% 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 the `User` dataclass to have an additional attribute `groups`
# 2. Use aggregation
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj dataclass `User`, aby miał dodatkowy atrybut `groups`
# 2. Użyj agregacji
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# @dataclass
# class User:
#     firstname: str
#     lastname: str
#     groups: ...

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

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

>>> from inspect import isclass

>>> assert isclass(User), \
'Object `User` has an invalid type; expected: `class`.'

>>> result = User('Alice', 'Apricot', groups=[
...     Group(gid=1, name='users'),
...     Group(gid=2, name='staff'),
... ])
>>>
>>> assert type(result) is User, \
'Result has an invalid type; expected: `User`.'

>>> assert hasattr(result, 'groups'), \
'Result has an invalid attribute; expected: to have an attribute `groups`.'

>>> assert type(result.groups) is list, \
'Result has an invalid attribute; expected: `groups` to be of type `list`.'
"""

# %% 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
from dataclasses import dataclass

# %% Types
User: type
Group: type

# %% Data
@dataclass
class Group:
    gid: int
    name: str

# %% Result
@dataclass
class User:
    firstname: str
    lastname: str

# %% About
# - Name: Dataclass Relations Composition
# - Difficulty: easy
# - Lines: 1
# - Minutes: 1

# %% 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 the `User` dataclass to have an optional attribute `friend`
# 2. Use forward reference
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj dataclass `User`, aby miał opcjonalny atrybut `friend`
# 2. Użyj odwołania w przód
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# @dataclass
# class User:
#     firstname: str
#     lastname: str
#     friend: ...

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

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

>>> from inspect import isclass

>>> assert isclass(User), \
'Object `User` has an invalid type; expected: `class`.'

>>> result = User('Alice', 'Apricot', friend=User('Bob', 'Blackthorn'))
>>>
>>> assert type(result) is User, \
'Result has an invalid type; expected: `User`.'

>>> assert hasattr(result, 'friend'), \
'Result has an invalid attribute; expected: to have an attribute `friend`.'

>>> assert type(result.friend) is User, \
'Result has an invalid attribute; expected: `friend` to be of type `User`.'
"""

# %% 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
from dataclasses import dataclass

# %% Types
User: type

# %% Data
@dataclass
class Group:
    gid: int
    name: str

# %% Result
@dataclass
class User:
    firstname: str
    lastname: str

# %% About
# - Name: Dataclass Relations Syntax
# - Difficulty: easy
# - Lines: 1
# - Minutes: 1

# %% 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. Use Dataclass to define class `Point` with attributes:
#    - `x: int` with default value `0`
#    - `y: int` with default value `0`
# 2. Use Dataclass to define class `Path` with attributes:
#    - `points: list[Point]`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Użyj Dataclass do zdefiniowania klasy `Point` z atrybutami:
#    - `x: int` z domyślną wartością `0`
#    - `y: int` z domyślną wartością `0`
# 2. Użyj Dataclass do zdefiniowania klasy `Path` z atrybutami:
#    - `points: list[Point]`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# @dataclass
# class Path:
#     points: ...

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

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

>>> from inspect import isclass

>>> assert isclass(Point), \
'Object `Point` has an invalid type; expected: `class`.'

>>> assert isclass(Path), \
'Object `Path` has an invalid type; expected: `class`.'

>>> assert hasattr(Point, 'x'), \
'Object `Point` has an invalid attribute; expected: to have an attribute `x`.'

>>> assert hasattr(Point, 'y'), \
'Object `Point` has an invalid attribute; expected: to have an attribute `y`.'


>>> Point()
Point(x=0, y=0)
>>> Point(x=0, y=0)
Point(x=0, y=0)
>>> Point(x=1, y=2)
Point(x=1, y=2)

>>> Path([Point(x=0, y=0),
...       Point(x=0, y=1),
...       Point(x=1, y=0)])
Path(points=[Point(x=0, y=0), Point(x=0, y=1), Point(x=1, y=0)])
"""

# %% 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
from dataclasses import dataclass

# %% Types
Point: type
Path: type

# %% Data
@dataclass
class Point:
    x: int = 0
    y: int = 0

# %% Result
@dataclass
class Path:
    ...