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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Optimization of I/O Workloads by Profiling in Python
  • What Is Pydantic?
  • Understanding the Fan-Out/Fan-In API Integration Pattern
  • Process Mining Key Elements

Trending

  • DZone's Article Submission Guidelines
  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Docker Base Images Demystified: A Practical Guide
  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 user avatar
Sameer Shukla
DZone Core CORE ·
Dec. 31, 23 · Analysis
Likes (5)
Comment
Save
Tweet
Share
4.6K Views

Join the DZone community and get the full member experience.

Join For Free

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
  • Process Mining Key Elements

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!