So all four of these approaches to structure data on their surface work more or less the same to keep data well structured.

Are there any reasons, be they hidden performance issues/enhancements, stylistic preferences, or just plain ol' pythonic/un-pythonic ways of doing stuff to prefer one approach over the others?

from typing import NamedTuple
from collections import namedtuple
from dataclasses import dataclass

# Normal class
class X:
    def __init__(self, a, b):
        self.a: int = a
        self.b: int = b

# Normal namedtuple
Y = namedtuple(
    'a b'

# With Inheretence
class Z(NamedTuple):
    a: int
    b: int

# Dataclass
class A:
    a: int
    b: int

All declared the same way

x = X(1, 2)
y = Y(3, 4)
z = Z(5, 6)
a = A(7, 8)

Accessed the same way

print(x, x.a, x.b)
print(y, y.a, y.b)
print(z, z.a, z.b)
print(a, a.a, a.b)

With basically the same results

<__main__.X object at 0x7c77f9b32e10> 1 2
Y(a=3, b=4) 3 4
Z(a=5, b=6) 5 6
A(a=7, b=8) 7 8

1 Answer 1


The last line of The Zen of Python is

Namespaces are one honking great idea -- let's do more of those!

And you have demonstrated that there are four ways to do namespaces. This does seem to conflict with the lines

There should be one-- and preferably only one --obvious way to do it.

Although that way may not be obvious at first unless you're Dutch.

But I think it gets down to intent. A class can potentially contain both data and methods. A namedtuple can only have data. Having a class that descends from a namedtuple indicates the data is distinct from the child class's methods and is not to be thought of as a unit. The dataclass decorator adds init and repr special methods to a class that does not do any computation with its initialization parameters.

To dive deeper into the intent behind adding these constructs to the language you should read the PEPs that led to them being added to the language (other than the bare class). They are referenced in the documentation for each of the modules you are importing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.