DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Optimization of I/O Workloads by Profiling in Python
  • What Is Pydantic?
  • Understanding the Fan-Out/Fan-In API Integration Pattern
  • Beyond Partitioning and Z-Order: A Deep Dive into Liquid Clustering for Unity Catalog Managed Tables

Trending

  • The Pipeline Failed, But the Infrastructure Changed
  • Building a Windows App for a Resilient SSH SOCKS Proxy and Selective Browser Routing
  • Build Production-Ready AI Phone Agents: Infrastructure, Models, and Telephony
  • 5 Mistakes Companies Make When Working With Staff Engineers

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. Enhancing Code Clarity With Python Namedtuples

Enhancing Code Clarity With Python Namedtuples

Learn how to create, de-structure, and optimize memory usage for cleaner, more readable code. Explore practical examples and best practices.

By 
Sameer Shukla
DZone Core CORE ·
Dec. 31, 23 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
6.0K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Python’s collection module has a feature called ‘Namedtuple’, a ‘Namedtuple’ is a tuple with named elements making code more expressive. Just like dictionaries in Python, ‘Namedtuple’ allows us to access the elements using a member of a tuple rather than an index.

Creating a Namedtuple

To create a namedtuple we have to use the function ‘namedtuple’ from the collection module.

Python
 
from collections import namedtuple

# Define a employee tuple that has fields id, name and location.
Employee = namedtuple ('Employee', 'id name location')

# Create instances of Employee
employee1 = Employee (id=10, name='John Doe', location='Atlanta')
employee2 = Employee (id=11, name='Mick', location='Dallas')


Accessing Elements From Namedtuple

'Namedtuple' provides a dual mechanism for element access. First, elements can be accessed through attribute names and the second mechanism uses traditional numeric indices. 

Python
 
print(f"{employee1.name} - {employee1.location}") # John Doe - Atlanta
print(f"{employee2.name} - {employee2.location}") # Mick – Dallas


Elements can be accessed using numeric indices as well. 

Python
 
print(f"{employee1[1]} - {employee1[2]}") # John Doe - Atlanta
print(f"{employee2[1]} - {employee2[2]}") # Mick – Dallas


Immutability

Immutability is a fundamental property of 'Namedtuples', inherited from regular tuples. It means once the value of the field is set during creation, it cannot be modified. 

Python
 
try:
    employee1.name = 'David'
except AttributeError as e:
    print(f"AttributeError: {e}") # AttributeError: can't set attribute


Methods

'namedtuple' not only provides a clean and readable way to structure the data but it also some useful methods, these methods enhance the functionality of 'Namedtuple'. 

a) _asdict(): The _asdict() method returns the named tuple as a dictionary, providing a convenient way to convert 'Namedtuples' into a format that is compatible with other data structures.

Python
 
employee1._asdict() # {'id': 10, 'name': 'John Doe', 'location': 'Atlanta'}


b) _replace(): The _replace() method creates a new instance of the 'Namedtuple' with specified fields replaced by new values. This method is crucial for maintaining immutability while allowing modifications.

Python
 
employee1_modified = employee1._replace(location='DFW')
employee1_modified # Employee(id=10, name='John Doe', location='DFW')


c) _make(): The _make(iterable) method creates a new instance of the 'namedtuple' from an iterable. For example, we can create a Namedtuple from the list using the _make() method.

Python
 
employee_list = [21, 'Bob','Gallup']
Employee._make(employee_list) # Employee(id=21, name='Bob', location='Gallup')


Unpacking Namedtuple

Through the process of unpacking, Python's 'Namedtuples' enables you to assign their values to individual variables in a single, concise statement.

Python
 
id, name, location = employee1
print(f"id: {id}, name: {name}, location:{location}")


Transforming 'Namedtuples' into different data structures

 You can convert a named tuple to a list by using the list() constructor. Here's an example:

Python
 
list(employee1) # [10, 'John Doe', 'Atlanta']


You can convert a named tuple to a dictionary using the '_asdict()' method, which returns an OrderedDict that you can convert to a regular dictionary. Here's an example: 

Python
 
dict(employee1._asdict()) # {'id': 10, 'name': 'John Doe', 'location': 'Atlanta'}


Advantages of Using ‘Namedtuple'

Readability: ‘Namedtuples’ make code more readable by providing meaningful names to elements, eliminating the need for index-based access.

Immutable: Like regular tuples, ‘Namedtuples’ are immutable. Once created, their values cannot be changed.

Memory Efficient: ‘Namedtuples’ is memory-efficient, consuming less space compared to equivalent classes. It's important to note that the memory efficiency gained by using Namedtuples is more common in scenarios involving a large number of instances or when dealing with large datasets.

Lightweight Data Structures: Ideal for creating simple classes without the need for custom methods.

Data Storage: Convenient for storing structured data, especially in scenarios where a full-fledged class is not necessary.

APIs and Database Records: Useful for representing records returned from databases or data received from APIs.

‘Namedtuple’ in Python is well-suited for scenarios where you need a simple, immutable data structure with named fields, such as 

Configuration settings: Use ‘Namedtuple’ to represent configuration settings with named fields for clarity and easy access.

Database Records: ‘Namedtuple’ can represent database records, making it clear which field corresponds to which column in a table.

Command-Line Parsing: Use ‘Namedtuple’ to store parsed command-line arguments, providing a clear structure for the input parameters.

Named Constants: ‘Namedtuple’ can be used to represent named constants in your code, providing a clear and readable way to define constant values.

'Namedtuples' excel in these scenarios by offering clarity, readability, and immutability, making them valuable tools for concisely structuring data.

IT Tuple Data (computing) Python (language) Open-source software

Opinions expressed by DZone contributors are their own.

Related

  • Optimization of I/O Workloads by Profiling in Python
  • What Is Pydantic?
  • Understanding the Fan-Out/Fan-In API Integration Pattern
  • Beyond Partitioning and Z-Order: A Deep Dive into Liquid Clustering for Unity Catalog Managed Tables

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook