Posts Named Tuples in Python
Post
Cancel

Named Tuples in Python

As I read the great book Python Tricks by Dan Bader I learned about named tuples and was pretty amazed about this. Named tuples can help you to make your code more structured and readable in certain circumstances. They can be used as an alternative to dicts or unstructured tuples. Here is how they work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> from collections import namedtuple
>>> Dog = namedtuple('Dog', 'breed color character') # same as the following
>>> Dog = namedtuple('Dog', ['breed', 'color', 'character'])
>>> rocky = Dog('pitbull', 'brown', 'excited')
>>> rocky.breed
'pitbull'
>>> rocky.color
'brown'
>>> rocky.character
'excited'
>>> rocky[1]
'brown'
>>> rocky
Dog(breed='pitbull', color='brown', character='excited')

The first argument of namedtuple is Dog, this is the type name as namedtuple cannot know the name of the variable. The variables of this class are either defined as a space separated single string or as an array of strings. You can then define a variable as Dog and then access the single variables as you would do it with every other class. Or even using an index as you would expect froma tuple.

If you forgot to assign a variable you get the following error.

1
2
3
4
>>> sunny = Dog('pitbull', 'brown')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __new__() missing 1 required positional argument: 'character'

As with regular tuples they are immutable.

1
2
3
4
>>> rocky.breed = 'bulldog'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

You can even add methods as the named tuples are build upon classes.

1
2
3
4
5
6
7
8
9
10
11
12
>>> class DogWithSound(Dog):
...     def bark(self):
...         if self.breed == 'pitbull':
...             print('WOOF')
...         elif self.breed == 'jack russel terrier':
...             print('woof woof woof')
...         else:
...             print('bark')
...
>>> princess = DogWithSound('pitbull', 'brown', 'lovely')
>>> princess.bark()
WOOF

A Python convention is that methods or variables starting with an _ underscore should be handled as private. However, this does not count for named tuples. They have a few integrated help methods, starting with an underscore but which belong to the public interface. This was done to prevent naming conflicts with the tuple fields the user defines. In the following a few help methods are shown.

1
2
3
4
5
6
>>> princess._asdict()
{'breed': 'pitbull', 'color': 'brown', 'character': 'lovely'}
>>> princess._replace(character='playful')
DogWithSound(breed='pitbull', color='brown', character='playful')
>>> Dog._make(['golden retriever', 'golden', 'happy'])
Dog(breed='golden retriever', color='golden', character='happy')

The method _asdict returns a dict representation of the named tuple. _replace creates flat copy of the tupel and returns the copy with the corresponding field changed. And _make creates a new object based on an iteratable object.

Resources

This post is licensed under CC BY 4.0 by the author.