/ Python

Python Gems #1: Named Tuples

In this series I'll present short Python snippets that I find amazing. Use at your own risk!

>>> # Ever stuck handling this ugly mess of tuple wrappings?!
>>> john = ("john", "somestreet", "3", "27")
>>> print(john[3]) # was this address or age again ...?

# Here is the solution!
>>> from collections import namedtuple
>>> Person = namedtuple('Person', ['name', 'street', 'housenumber', 'age'])
>>> john = Person("john", "somestreet", "3", "27")
>>> print(john)
Person(name='john', street='somestreet', housenumber='3', age='27')
>>> print(john.age)
27
>>> name, street, housenumber, age = john  # and you can use it just like the tuple it was before!