DEV Community

Cover image for Named Tuples in Python: what type are they?
guzmanojero
guzmanojero

Posted on

Named Tuples in Python: what type are they?

Named tuples in Python are an extension of the built-in tuple data type, allowing you to give meaningful names to the elements of a tuple. In others words, named tuples are tuples with named attributes. Isn't that cool?

They 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. Again, cool!!

Let's see how this works.

from collections import namedtuple 

P = namedtuple("Point", "x y")
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode
> class A:
    pass

> type(A)
class 'type'
Enter fullscreen mode Exit fullscreen mode

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'

Enter fullscreen mode Exit fullscreen mode

p is an instance of type Point. But it's also a tuple:

> print(isinstance(p, tuple))
True

Enter fullscreen mode Exit fullscreen mode

In summary:

  • P is a class generated dynamically by namedtuple.
  • Instances of P are objects of type Point that also subclass tuple.

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")
Enter fullscreen mode Exit fullscreen mode

I used a different name to make clear the distinction between thw two.

Top comments (0)