Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Tips and Traps¶
Prefer
Dataclasstonamedtuplefor many reasons.A namedtuple is immutable while a dataclass can be both mutable (
frozen=Falsewhich is the default) or immutable (frozen=True).
However, namedtuple does have one advantage over dataclass. Members of a namedtuple is assible both via the dot operator and index. In situations where both dot accessing and index accessing of members is required, a namedtuple comes handy. For examples, a list of namedtuple objects can be used as the data for creating a pandas DataFrame but not a list of dataclass objects.
dataclass - mutable¶
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int = 10Person("Ben")Person(name='Ben', age=10)p = Person("Ben", 34)
pPerson(name='Ben', age=34)str(p)"Person(name='Ben', age=34)"dataclass - immutable¶
Attributes of the class Person is mutable
since frozen=False (default).
p.age = 20
pPerson(name='Ben', age=20)@dataclass(frozen=True)
class PersonImmutable:
name: str
age: int = 10PersonImmutable("Ben")PersonImmutable(name='Ben', age=10)p = PersonImmutable("Ben", 30)
pPersonImmutable(name='Ben', age=30)Attribute of PersonImmutable is immutable since frozen=True.
p.age = 20
FrozenInstanceErrorTraceback (most recent call last)
<ipython-input-22-b29e99bf1482> in <module>
----> 1 p.age = 20
<string> in __setattr__(self, name, value)
FrozenInstanceError: cannot assign to field 'age'namedtuple¶
from collections import namedtuplePersonNT = namedtuple("PersonNT", ["name", "age"])p = PersonNT("Ben Du", 30)
pPersonNT(name='Ben Du', age=30)p[0]'Ben Du'p[1]30Objects of namedtuple as pandas DataFrame Data¶
import pandas as pdpd.DataFrame(data=[p])