Named Tuples in Python: what are they anyway?
guzmanojero
Posted on November 17, 2024
Named tuples are part of the collections
module and provide a way to define simple, immutable classes in a simpler way.
Wait what, classes?
Yes, classes.
Named tuples are essentially immutable classes.
This is the magic that occurs: when you create a named tuple using namedtuple
, the result is not an instance of the tuple itself, but rather a dynamically generated class that inherits from tuple
. Cool, isn't it?
Let's see how this works.
from collections import namedtuple
P = namedtuple("Point", "x y")
When you run P = namedtuple("Point", "x y")
, you are creating a new class named Point
(as specified in the first argument to namedtuple).
The namedtuple
function uses type
behind the scenes to dynamically create a new class named Point
that inherits from tuple
. This new class is stored in the variable P
.
And as with classes, the type is type
.
> type(P)
class 'type'
> class A:
pass
> type(A)
class 'type'
And what type is the instance of a namedtuple?
from collections import namedtuple
P = namedtuple("Point", "x y")
p = P(1,2)
> print(type(p))
class '__main__.Point'
p
is an instance of type Point
. But it's also a tuple:
> print(isinstance(p, tuple))
True
In summary:
-
P
is a class generated dynamically bynamedtuple
. - Instances of
P
are objects of typePoint
that also subclasstuple
.
And one last thing:
It's very common to name the namedtuple variable (what we called P
) with the same name as the type name (what we called Point
), the dynamically created class:
from collections import namedtuple
Point = namedtuple("Point", "x y")
I used a different name to make clear the distinction between thw two.
Posted on November 17, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.