Skip to main content
Taught by Tech Leads

Master pipelines, cloud & AI to become an operational Data Engineer.

DataScientist.fr
Image de Named Tuples in Python with namedtuple - Practical Tutorial
Python

Named Tuples in Python with namedtuple - Practical Tutorial

Photo de Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Published on 2 janvier 2025 · 12 min of reading

In the world of programming, writing clear and understandable code is essential for the maintenance and evolution of projects. Among the tools available to achieve this goal, namedtuple stands out as an elegant and efficient solution. This data structure, from the collections module in Python, offers the simplicity of tuples with the additional advantage of explicit field names. Discover how namedtuple can transform your code into a readable and structured work, while exploring its many features and practical applications.

Using namedtuple to write readable code

To write clean and readable code in Python, using namedtuple from the collections library is a wise practice. A namedtuple is a subclass of tuple that allows you to assign names to each data position, significantly improving the readability and maintainability of the code.

Creating a namedtuple

Creating a namedtuple is simple and effective. For example, to represent a point in two dimensions, you can define a namedtuple like this:
python
Here, Point is the name of the namedtuple, and ['x', 'y'] are the field names. This means we can now create instances of Point with values for x and y.

Using namedtuple

One of the major advantages of namedtuple is the accessibility of attributes by name, which makes the code more expressive:
python
Instead of accessing elements by index like with a standard tuple, you use the field names. This makes the code clearer, especially when the number of fields increases.

Comparison with standard tuples

Let's compare a standard tuple and a namedtuple:
python
Accessing by name is more intuitive and self-documenting, which makes understanding the code easier.

Additional advantages

In addition to improving readability, namedtuple offers other advantages, such as immutability, meaning its instances cannot be modified after creation. This enhances code safety by preventing accidental modifications.
Moreover, namedtuple includes useful methods such as _replace(), which allows creating a modified copy of the instance:
python
This method is particularly useful for maintaining declarative structures while allowing necessary adjustments without altering the original object.
In summary, namedtuple is a powerful feature of Python that contributes to code clarity and robustness, while providing a simple and intuitive interface.

Creating tuple-like classes with namedtuple

Creating tuple-like classes with namedtuple is an effective technique for structuring data without the complexity associated with fully defining a class. This allows you to benefit from the simplicity of tuples while adding the readability and clarity of classes with named attributes.

Defining a namedtuple as a class

Although namedtuple is not a full-fledged class in the traditional sense, it offers an interface that is quite similar. For example, if you were to create a class for a student with a name and an age, it could look like this using namedtuple:
python
With this definition, you can create student instances in a concise and clear manner:
python

Comparison with a traditional class

Creating a traditional class in Python requires more code, and while it offers more flexibility, it is not always necessary:
python
Here, namedtuple provides the same functionality with less code and a simpler syntax.

Methods and immutability

Instances of namedtuple are immutable, meaning once created, you cannot modify their attributes. This ensures that the data remains constant, which can prevent potential errors:
python
However, you can use the _replace() method to create a new instance with modifications:
python
In conclusion, namedtuple offers an elegant and efficient solution for creating data structures similar to classes, while maintaining the simplicity and efficiency of tuples.

Exploring additional features of namedtuple classes

The use of namedtuple is not limited to assigning names to fields. This structure also offers additional features that enhance the efficiency and flexibility of your code. Let's explore these advanced features that make namedtuple even more powerful and versatile.

Method _fields

Each namedtuple has a _fields attribute that returns a list of field names. This can be useful for dynamic inspection of available fields, particularly in contexts where the code needs to adapt to different data structures:
python

Method _asdict

The _asdict() method is extremely useful for converting a namedtuple into an ordered dictionary. This allows for easy integration with functions that require inputs in the form of dictionaries, or for more flexible data manipulation:
python
This feature is particularly valuable during serialization or when dealing with complex data processing.

Adding default behaviors

A namedtuple can be extended with default values for certain fields, simplifying the creation of instances. This is done by defining a new subclass and using the _replace() method to assign default values:
python
Thus, namedtuple can incorporate default behaviors without complicating the syntax, keeping the code both elegant and functional.
These additional features make namedtuple a powerful tool for managing simple and complex data structures with efficiency and readability, while offering advanced capabilities for data manipulation and transformation.

Writing readable code with namedtuple

Writing readable code is an essential skill for developers, and using namedtuple in Python can greatly facilitate this task. Thanks to its ability to associate meaningful names with the elements of a tuple, namedtuple enhances the clarity and understanding of the code.

Clarity through explicit names

With namedtuple, each field is associated with an explicit name, which helps avoid the ambiguity often present with standard tuples. Let's take the following example:
python
Here, the names title, author, and year make the code self-documenting, thus facilitating its reading and maintenance by other developers.

Reducing errors

Accessing elements by name rather than by index reduces the risk of errors. With a standard tuple, it is easy to confuse indices, especially if the tuple contains many elements:
python
This clarity reduces the risk of errors when reading and modifying the code.

Improved documentation and collaboration

namedtuple also facilitates collaboration within teams. Developers can quickly understand the data structure without having to consult external documentation. This is particularly useful in large projects where multiple people are working on the same code.

Use in complex contexts

In more complex contexts, such as with APIs or databases, namedtuple can help structure data in an orderly and comprehensible way:
python
By using namedtuple, you can structure and manipulate data intuitively, which allows for producing readable and maintainable code in the long term.

Using namedtuple compared to other data structures

When it comes to choosing the right data structure in Python, namedtuple offers a unique combination of simplicity and readability. However, it is important to understand how it compares to other available data structures, such as tuples, dictionaries, and regular classes.

Comparison with standard tuples

Standard tuples are lightweight and immutable, making them ideal for storing fixed collections of values. However, accessing elements is done by index, which can make the code difficult to understand, especially when tuples contain many elements:
python
With namedtuple, accessing elements by name makes the code more explicit and readable.

Comparison with dictionaries

Dictionaries allow access to data by key, which is similar to accessing by name in namedtuple. However, dictionaries are mutable and do not guarantee the order of elements (until Python 3.7, where insertion order is preserved). namedtuple offers immutability and a more concise syntax for fixed data structures:
python
While dictionaries are more flexible, namedtuple provides a more defined structure with explicitly named fields.

Comparison with regular classes

Classes offer maximum flexibility with the ability to add methods and behaviors, but they require more code to set up. namedtuple is better suited when you need a lightweight structure with named fields, without the overhead of a full class:
python
In summary, namedtuple is ideal for simple and immutable data structures, where readability and clarity are priorities. For more complex needs, classes and dictionaries may offer the necessary flexibility.

Subclassing namedtuple classes

Although namedtuple is often used to create simple and efficient data structures, it is also possible to subclass namedtuple to add additional functionality. This allows you to combine the simplicity of namedtuple with the power of Python classes.

Creating a subclass of namedtuple

To subclass a namedtuple, you start by defining the base namedtuple, and then create a new class that inherits from it. For example, if we want to add a method to a namedtuple representing a point in 2D, we can do it as follows:
python
In this example, PointWithDistance inherits the properties of Point and adds a method to calculate the distance to the origin.

Adding methods and behaviors

Subclassing a namedtuple allows you to enrich its functionality by adding specific methods that would not otherwise be available. This is particularly useful for encapsulating logic related to the data without compromising simplicity:
python

Limitations and considerations

Despite these advantages, it is important to note that namedtuple is immutable. This means that you cannot modify values after they are created, even in a subclass. If your application requires mutable objects, a standard Python class may be more appropriate.
Finally, when subclassing, ensure that adding new methods does not compromise the immutability and simplicity that make namedtuple strong. Use this technique to enhance functionality while preserving the data structure.

Measuring creation time: tuple vs namedtuple

Comparing performance between a standard tuple and a namedtuple is an important step in understanding the impact of using namedtuple in terms of creation time and efficiency. While namedtuple offers better readability, it is essential to measure its performance cost.

Setting up the test environment

To evaluate creation time, we can use Python's timeit module, which is ideal for measuring the execution time of small pieces of code. Here’s how we can set up our test:
python

Measuring creation time

We will now measure the time required to create one million tuples and one million namedtuple:
python

Results and interpretation

In general, results show that creating a namedtuple is slightly slower than creating a standard tuple. This is due to the fact that namedtuple has to manage additional metadata for field names.
This difference, while noticeable in a performance test, is often negligible in practical applications where the benefits of readability and maintainability outweigh the slight decrease in performance.
In conclusion, although namedtuple may be slightly slower to create, its use is justified by the improvement in code readability and structure, especially in cases where data clarity is paramount.

Conclusion

In conclusion, using namedtuple in Python represents an optimal balance between simplicity, readability, and functionality. As developers, we constantly seek to write code that not only works correctly but is also easy to understand and maintain. namedtuple stands out in this aspect by providing a lightweight and efficient structure for handling datasets, while allowing intuitive and clear access through explicit field names.

Advantages and use cases

One of the main advantages of namedtuple is its ability to make the code self-documenting, which greatly facilitates collaboration and code review. In development environments where multiple people work on the same project, this clarity can significantly reduce errors and improve productivity.
Moreover, with features like _asdict() and subclassing, namedtuple can be adapted to meet a multitude of needs, ranging from simple data structures to more complex extensions requiring specific behaviors.

Performance considerations

Although our performance tests showed that creating namedtuple is slightly slower than a standard tuple, this impact is generally insignificant in most applications. The benefits in terms of readability and structure far outweigh this slight performance difference. However, in very specific cases where performance is critical and millions of objects need to be created in a short time, it may be wise to weigh these considerations.

Integration with other data structures

Finally, namedtuple integrates well with other Python data structures, offering flexibility that allows developers to choose the best approach based on the specific requirements of their project. Whether for structuring API responses, manipulating data from databases, or simply organizing information within a program, namedtuple provides an elegant and pragmatic solution.
By adopting namedtuple in appropriate situations, developers can improve the overall quality of their code, making it not only functional but also clear and maintainable, which is essential in modern software development.

Want to go further?

This topic is part of our Become a Data Analyst course. Browse the full programme, or get it by email.

Share with

Photo de Romain DE LA SOUCHÈRE

Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Expert Data Engineering et Cloud, Romain affiche plus de 11 ans d'expérience, dont plusieurs années comme Lead Developer sur des solutions Smart Building haute performance. Il y a conçu et mis en production des moteurs de traitement capables d'absorber des centaines de milliers de données de capteurs par minute, ainsi que des bases clusterisées gérant plus de 10 millions de données dynamiques. Certifié Microsoft Azure DevOps Engineer Expert, il maîtrise aussi bien le développement back-end (Python, C#) que le DevOps (Docker, Kubernetes, Terraform) et les agents LLM. Formateur en Python, cloud, DevOps et IA générative appliquée, il forme avec une obsession : Amener chaque apprenant à concevoir et déployer des architectures réellement scalables en production.

» Learn More

Associated trainings

All our trainings
Image de la formation Become a Data Analyst
Become a Data Analyst
6 months
Intermediate
Guarantee
Image de la formation Become a Data Engineer
Become a Data Engineer
9 months
Advanced
Guarantee

Associated articles

See all our articles