Adventures in Machine Learning

Enhance Readability with Python Namedtuple – The Immutable Object

Python Namedtuple: Anto Immutable Objects with Enhanced Readability

Python is a versatile programming language that comes with a wide range of in-built data structures such as list, tuple, dict, and set. Another such data structure is called a Namedtuple.

It is an immutable object with a structure that is easy to read and comprehend by humans. In this article, we will explore Python Namedtuple by discussing its definition, syntax, and examples.

Additionally, we will delve into its functionalities, such as accessing attributes, handling invalid keys, renaming variables, and using the Namedtuple module functions like _make(iterable), _asdict() and _replace(**kwargs).

Python Namedtuple: Definition and Functionality

A Namedtuple is an immutable data structure that creates a new class with specific field names and values.

It is defined as a subclass of tuple, where each field has a name. In contrast to a regular tuple, Namedtuples are easier to use and read – providing meaningful field names instead of numerical indices.

Namedtuples offer several advantages over regular lists, and some of these include better readability, enhanced code compilation time, and specific memory optimizations. They can be created using Python’s collections module by importing the namedtuple function:

“`

from collections import namedtuple

“`

Syntax and Example

Syntax:

You can create an object of a Namedtuple by using a factory function – namedtuple(). Here is its syntax:

“`

namedtuple(typename, field_names[, verbose=False][, rename=False][, defaults=None]

“`

There are two mandatory arguments and two optional arguments.

The mandatory arguments are:

– **typename:** A string that represents the name of the namedtuple. It also specifies the class name for the new type.

– **field_names:** A string or an iterable sequence of strings that contains the field names separated by commas or spaces. The optional arguments are:

– **verbose:** A Boolean value that specifies whether to print the class definition onscreen.

– **rename:** A Boolean value that specifies if invalid field names are to be automatically replaced with positional names. – **defaults:** Values for default fields.

Example:

To create a namedtuple, we need to call the function namedtuple() and pass in the typename and field_names as shown below:

“`python

Point = namedtuple(‘Point’, [‘x’, ‘y’])

# Or, this can also be done like this

Point = namedtuple(‘Point’, ‘x y’)

“`

After creating Point, an instance of the class can then be instantiated as shown below:

“`python

pt = Point(1, 2)

“`

The resulting output should be:

“`python

print(pt.x) # Output: 1

print(pt.y) # Output: 2

“`

Python Namedtuple Functionalities

Access Attributes using getattr() Function

In Python, there is a getattr() function that is used to obtain an attribute from an object by using its name. The getattr() function takes two arguments.

The first argument is the object whose attribute is to be obtained, while the second argument is the attribute’s name. Here’s an example:

“`python

from collections import namedtuple

Person = namedtuple(“Person”, “name age”)

def display_person_information(info):

name = getattr(info, “name”)

age = getattr(info, “age”)

print(f”Name: {name}, Age: {age}”)

person1 = Person(“John Doe”, 35)

display_person_information(person1)

“`

The output of this code snippet should be:

“`

Name: John Doe, Age: 35

“`

Handling Invalid Keys

Sometimes, we may mistakenly pass an invalid key while attempting to access a Namedtuple. In such cases, a ValueError is raised.

The exception usually says that the key is not found in the field names of the Namedtuple. To avoid this exception, we can catch it and handle it appropriately.

Here’s an example:

“`python

from collections import namedtuple

Person = namedtuple(“Person”, “name age”)

person1 = Person(“John Doe”, 35)

try:

print(person1.gender)

except ValueError:

print(“

Invalid field name”)

“`

The output of this code snippet should be:

“`

Invalid field name

“`

Rename Variable

In Namedtuples, we can change the name of any field by using the _replace() method. Here is how it is done:

“`python

from collections import namedtuple

Person = namedtuple(“Person”, [“name”, “age”])

person1 = Person(name=”John”, age=35)

person2 = person1._replace(name=”Jane”)

print(person1)

print(person2)

“`

The output of this code snippet should be:

“`

Person(name=’John’, age=35)

Person(name=’Jane’, age=35)

“`

Namedtuple Module

The Namedtuple module offers a variety of attributes that can be useful in programming. Some of the most useful attributes include _fields, _fields_defaults, and default fields.

_fields attribute: It returns a tuple of all the fields in the Namedtuple. “`python

from collections import namedtuple

Person = namedtuple(“Person”, [“name”, “age”])

print(Person._fields)

“`

The output of this code snippet should be:

“`

(‘name’, ‘age’)

“`

_fields_defaults attribute: This attribute returns an ordered dictionary that contains the field names and their corresponding default values. “`python

from collections import namedtuple

Person = namedtuple(“Person”, [“name”, “age”], defaults=[“New Person”, 20])

print(Person._fields_defaults)

“`

The output of this code snippet should be:

“`

OrderedDict([(‘name’, ‘New Person’), (‘age’, 20)])

“`

Default fields: Default fields are specified during the creation of the Namedtuple. They are useful when the fields are optional and do not necessarily need to have a value.

“`python

from collections import namedtuple

Person = namedtuple(“Person”, [“name”, “age”], defaults=[“Unknown”, None])

person1 = Person(name=”Jonah”)

print(person1)

“`

The output of this code snippet should be:

“`

Person(name=’Jonah’, age=None)

“`

_make(iterable) Function

The _make(iterable) function creates a new instance of the Namedtuple by passing an iterable/generator as its argument. Here’s an example:

“`python

from collections import namedtuple

Product = namedtuple(“Product”, [“product_name”, “category”, “price”])

data = [“Meat”, “Protein Sources”, “$12.50”]

p1 = Product._make(data)

print(p1.product_name)

print(p1.category)

print(p1.price)

“`

The output of this code snippet should be:

“`

Meat

Protein Sources

$12.50

“`

_asdict() Function

The _asdict() function of Namedtuple is used to convert the Namedtuple into an ordered dictionary. An ordered dictionary is similar to a regular dictionary, but it preserves the insertion order of keys.

“`python

from collections import namedtuple

Person = namedtuple(“Person”, [“name”, “age”])

person1 = Person(“John Doe”, 35)

person2 = Person(“Jane Doe”, 20)

print(person1._asdict())

print(person2._asdict())

“`

The output of this code snippet should be:

“`

OrderedDict([(‘name’, ‘John Doe’), (‘age’, 35)])

OrderedDict([(‘name’, ‘Jane Doe’), (‘age’, 20)])

“`

_replace(**kwargs) Function

This function returns a new instance of the Namedtuple with the specified fields in the arguments replaced with new values. Here’s an example:

“`python

from collections import namedtuple

Person = namedtuple(“Person”, [“name”, “age”])

person1 = Person(“John Doe”, 35)

person2 = person1._replace(name=”Jane Doe”, age=20)

print(person1)

print(person2)

“`

The output of this code snippet should be:

“`

Person(name=’John Doe’, age=35)

Person(name=’Jane Doe’, age=20)

“`

** (Double Star) Operator

The ** operator can be used to create a dictionary from the fields of a Namedtuple. Here’s an example:

“`python

from collections import namedtuple

Product = namedtuple(“Product”, [“product_name”, “category”, “price”])

p1 = Product(“Meat”, “Protein Sources”, “$12.50”)

p1_dict = {**p1._asdict()}

print(p1_dict)

“`

The output of this code snippet should be:

“`

{‘product_name’: ‘Meat’, ‘category’: ‘Protein Sources’, ‘price’: ‘$12.50’}

“`

Conclusion

In this article, we have discussed the various functionalities of Python Namedtuple such as accessing attributes, handling invalid keys, renaming variables, and using Namedtuple module functions like _make(iterable), _asdict(), and _replace(**kwargs). Python Namedtuple is an immutable data structure that creates a more readable and comprehensible data structure.

It is easy to use and offers numerous advantages over the regular tuple. By understanding these functionalities, you can utilize this powerful tool in your programming.

Python Namedtuple is an essential and useful data structure in Python that creates an immutable object with a structure that is easy to read and comprehend by humans. This article has discussed the definition, syntax, and example, along with various functionalities like accessing attributes, handling invalid keys, renaming variables, and using Namedtuple module functions like _make(iterable), _asdict(), and _replace(**kwargs).

By understanding these functionalities, you can utilize this powerful tool in your programming to create more readable and comprehensible data structures. Python Namedtuple is a fundamental topic that every Python developer should be familiar with.

Popular Posts