Python Namedtuple
Today I found a way to give a tuple a name in Python called namedtuple. A simple class can be built using collections.namedtuple
.
Related course: Complete Python Programming Course & Exercises
Python Namedtuple
The example below shows the creation of a named tuple. There are several ways to created namedtuples and to access their attributes.
from collections import namedtuple
# Define a namedtuple type User with the name, sex and age attributes.
User = namedtuple('User', ['name', 'sex', 'age'])
# Create a User object
user = User(name='jessica', sex='female', age=21)
# You can also create a User object from a list, note that you need to use the "_make" method here
user = User._make(['jessica', 'female', 21])
print(user)
# User(name='user', sex='female', age=21)
# Get the user's attributes
print(user.name)
print(user.sex)
print(user.age)
# Modify object properties, note the use of the "_replace" method
user = user._replace(age=22)
print(user)
# User(name='user', sex='female', age=22)
# Convert the User object to a dictionary, note the use of "_asdict"
print(user._asdict())
# OrderedDict([('name', 'jessica'), ('sex', 'female'), ('age', 22)])
python namedtuple vs tuple
Python tuples should be very familiar to everyone. It can store a sequence of Python objects. Unlike list, you can't change the value of an element in a tuple. the elements of a tuple are accessed via an index:
Tuple also has a brother named named namedtuple, both of which are tuples, but more powerful. For namedtuple, you don't have to access it by indexing values anymore, you can think of it as a dictionary accessed by name, except that the values in it cannot be changed.
>>> from collections import namedtuple
>>> Animal = namedtuple('Animal','name age type')
>>> bob = Animal(name="bob newton", age=5, type="cat")
>>>
>>> print(bob)
Animal(name='bob newton', age=5, type='cat')
>>>
>>> print(bob.name)
bob newton
>>>
>>> print(bob.type)
cat
>>>
In order to construct a namedtuple two parameters are needed, the name of the namedtuple and the name of the domain in it. For example, in the above example, the name of the tuple is "Animal", which includes three domains, namely "name", "age" and "type".
>>> Animal = namedtuple('Animal','name age type')
Namedtuple has better readability than regular tuples and can make the code easier to maintain. It is also lighter and more efficient than a dictionary.
>>> print(bob.name)
>>> print(bob.type)
Python Namedtuple with invalid keys
One thing to note, however, is that the properties in the namedtuple are immutable. Any attempt to change its property values is not accepted.
>>> bob.age = 6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
>>>
Another very good thing about Namedtuple is that it is fully compatible with the tuple. That is, we can still use the index to access a namedtuple.