1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Dataclass in Python. Useful when mainly need to store / change attributes of an instance.
# Can be seen as a special, structured data type.
import sys
from dataclasses import dataclass, field, FrozenInstanceError


# Basic dataclass
@dataclass
class Coffee:
    name: str
    white: bool = True
    addons: list[str] = field(default_factory=list)  # provide default empty list, avoiding referencing "[]" object


# "Lightweight" (faster) dataclass with slots, no __dict__ dictionary
@dataclass(slots=True)  # default - False
class CoffeeWSlots:
    name: str
    white: bool = True
    addons: list[str] = field(default_factory=list)


# Frozen dataclass
@dataclass(frozen=True)  # cannot change class attrs after initializing
class CoffeeConst:
    name: str
    white: bool = True
    addons: list[str] = field(default_factory=list)


if __name__ == "__main__":
    c = Coffee(name="Espresso", white=False)
    c_slots = CoffeeWSlots(name="Espresso", white=False)
    c_const = CoffeeConst(name="Espresso", white=False)

    c.name = "Espresso1"
    try:
        c_const.name = "Espresso1"
    except FrozenInstanceError:
        print("Cannot change frozen dataclass")
    print(c, sys.getsizeof(c), c.__dict__)
    try:
        print(c_slots.__dict__)
    except AttributeError:
        print("No __dict__ dunder in a class with slots")
    print(c_slots, sys.getsizeof(c_slots))
    print(c_const, sys.getsizeof(c_slots))