Lately, I integrated namedtuples in my Python programming vocabulary. They allow you to create data structure classes in one line.
Start by importing them from
from collections import namedtuple
Define a new class as a
Person = namedtuple("Person", ("firstname", "lastname"))
You can know create new instances of Person, as you would do with any other class:
john = Person("John", "Doe")
And if you print it:
In : print(john) Person(firstname='John', lastname='Doe')
(yes, I use IPython, don't you?)
Now let's see what namedtuples give you.
In : f,l = john In : f Out: 'John' In : l Out: 'Doe'
Field access by name:
In : john.firstname Out: 'John' In : john.lastname Out: 'Doe'
You also have access by index:
In : john Out: 'John' In : john Out: 'Doe'
(OK, I tried some stuff during the redaction of the article)
And that means you can iterate on them, great!
In : for value in john: ....: print(value) ....: John Doe
You can retrieve the indexes of defined values (like in tuples):
In : john.index('Doe') Out: 1
And count the occurrences of the values for free (also like in tuples, which is useless in my example)
In : john.count('John') Out: 1
There's more. Contrary to classes, equality is defined for you for free:
In : john2 = Person('John', 'Doe') In : john == john2 Out: True
And last but not least, like standard tuples, namedtuples are immutable
In : john.firstname = "Billy" --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-34-a7d9f29302d8> in <module>() ----> 1 john.firstname = "Billy" AttributeError: can't set attribute
This last one is awesome.
So what is cool with all that? The great strength of tuples is that they are immutable, unlike lists. Thats why, when you have an array of values that is not subject to change, you should consider to create it as a tuple by default. Tuples are memory efficient and give you the insurance that nothing will alter them in your application. Besides, the syntax to create them is a bit shorter:
In : t = 1, 2, 3, 4, 5 # you don't even need the parens! In : t Out: (1, 2, 3, 4, 5)
Named tuples extends this ability to any data structure you could create, giving you access to fields by name for readability.
The only drawback is that you cannot define methods or properties on them, as you could do in immutable data structures in other languages. Yet it is still a nice feature of Python.