Skip to content
Go back

Namedtuples

Published:  at  09:34 AM
1 min read

Out of the handy collections module, I’m using namedtuple datatype the most.

Once instantiated, namedtuples can be used like regular tuples:

>>> from collections import namedtuple

>>> Dog = namedtuple('Dog', 'age breed color')
>>> rachel = Dog(2, 'Pomeranian', 'Brown')

>>> rachel[0]
2

>>> name, breed, color = rachel
>>> color
'Brown'

With the advantage of accessing the fields by attribute (name) lookup:

>>> rachel.breed
'Pomeranian'

And an awesome string __repr__() with a name=value style:

>>> rachel
Dog(age=2, breed='Pomeranian', color='Brown')

Main Use cases

I found namedtuple especially useful when:

Tips & tricks

>>> rachel.color = 'Tan'
AttributeError: "can't set attribute"

>>> rachel._replace(color='Tan')
Dog(age=2, breed='Pomeranian', color='Tan')
>>> pepsi = {'age': 12, 'breed': 'Belgian Shepherd', 'color': 'Black'}
>>> Dog(**dict)
Dog(age=12, breed='Belgian Shepherd', color='Black')



Previous Post
lean() on
Next Post
No Demon!