Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Tips and Traps

  1. Prefer Dataclass to namedtuple for many reasons.

    • A namedtuple is immutable while a dataclass can be both mutable (frozen=False which 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 = 10
Person("Ben")
Person(name='Ben', age=10)
p = Person("Ben", 34)
p
Person(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
p
Person(name='Ben', age=20)
@dataclass(frozen=True)
class PersonImmutable:
    name: str
    age: int = 10
PersonImmutable("Ben")
PersonImmutable(name='Ben', age=10)
p = PersonImmutable("Ben", 30)
p
PersonImmutable(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 namedtuple
PersonNT = namedtuple("PersonNT", ["name", "age"])
p = PersonNT("Ben Du", 30)
p
PersonNT(name='Ben Du', age=30)
p[0]
'Ben Du'
p[1]
30

Objects of namedtuple as pandas DataFrame Data

import pandas as pd
pd.DataFrame(data=[p])
Loading...