Python Showdown: Namedtuple vs SimpleNamespace vs DataClass

Python users, ever needed a light data container (like a dictionary) but wanted to access members using the dot (.) notation?

There are a couple of options to choose from: namedtuple, SimpleNamespace
and dataclass.

Here's how they all differ:

1️⃣ namedtuple: immutable, memory efficient, iterable and members can be accessed by index as well. Static and somewhat verbose.

2️⃣ simple_namespace: mutable, uses more memory than namedtuple, not iterable nor indexable. Flexible and less verbose.

3️⃣ dataclass: can be mutable or not (controlled by frozen parameter), can set default attributes, has special methods like repr (how it's displayed) and eq (check if it's equal to another instance). Uses more memory and is relatively newly-introduced (Python 3.7).

No alt text provided for this image

When to use which?
➡ namedtuple: You need something light on memory and immutable

➡ simple_namespace: You need flexibility to change the attributes or even
add them dynamically with little boilerplate.

➡ dataclass: You want more flexibility and control.

🔔 Follow me for more insights on Python and Analytics. Thanks for reading!