Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

Python Namedtuple

A sequence of immutable objects is a Tuple.

Namedtuple enables the user to provide names to the elements in the Tuple. So, it provides the user with the option to access the elements either by index or by the designated name.

Thus, it increases the readability of the code.

Syntax:

collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)

typename: It depicts the name assigned to the nametuple object.

field-names: It is used to define the field names to the namedtuple.

rename: By setting the rename variable value to True, the user can rename the invalid fields to their corresponding index names.

defaults: It enables the user to define default values to the parameters that are optional.

module: __module__ attribute of the named tuple is set to the particular value, provided the module is defined.

Example:

from collections import namedtuple

Information = namedtuple('Information', ['city', 'state', 'pin_code'])

# below are also valid ways to namedtuple
# Employee = namedtuple('Employee', 'name age role')
# Employee = namedtuple('Employee', 'name,age,role')

info1 = Information('Pune', 'Maharashtra', 411027)
info2 = Information('Satara', 'Maharashtra', 411587)

for x in [info1, info2]:
    print(x)
print('\n')
print("Accessing the attributes via index values....")
# accessing via index value
for x in [info1, info2]:
    print(x)
print("Accessing the attributes via field name....")
# accessing via name of the field
for x in [info1, info2]:
    print(x.city, 'is in',x.state, 'with', x.pin_code)

Output:

Information(city='Pune', state='Maharashtra', pin_code=411027)
Information(city='Satara', state='Maharashtra', pin_code=411587)


Accessing the attributes via index values....
Information(city='Pune', state='Maharashtra', pin_code=411027)
Information(city='Satara', state='Maharashtra', pin_code=411587)
Accessing the attributes via field name....
Pune is in Maharashtra with 411027
Satara is in Maharashtra with 411587


Python Namedtuple functionalities

  • Access attributes using getattr() function
  • Python Namedtuple with invalid keys
  • rename variable
  • Namedtuple module
  • _make(iterable) function
  • _asdict() function
  • _replace(**kwargs) function
  • Namedtuple attributes
  • “**” (double star) operator

1. Access attributes using getattr() function

The getattr() function is used to access the attributes of the namedtuple.

from collections import namedtuple

Information = namedtuple('Information', ['city', 'state', 'pin_code'])

info1 = Information('Pune', 'Maharashtra', 411027)
info2 = Information('Satara', 'Maharashtra', 411587)

print (getattr(info1,'city'))

Output:

Pune

2. Python Namedtuple with invalid keys

If the user uses invalid names as field values/keys, then ValueError is generated.

from collections import namedtuple

Information = namedtuple('Information', ['city', 'state', 'pin_code'])

try:
    Information = namedtuple('Information', ['city', 'state', 'if '])

except ValueError as error:
    print(error)

Output:

Type names and field names must be valid identifiers: 'if '

3. rename variable

In case, the user uses invalid keys, we can set the rename variable to True.

By this, the keys are replaced by their index values.

from collections import namedtuple

Information = namedtuple('Information', 'if',  rename=True)

try:
    info1 = Information('Pune' )
    for x in [info1]:
        print(x)
except ValueError as error:
    print(error)

Output:

Information(_0='Pune')

4. Namedtuple module

from collections import namedtuple

Information = namedtuple('Information', 'city',  rename=True, module='Simple1')
print(Information.__module__)

Output:

Simple1

5. _make(iterable) function

from collections import namedtuple

Information = namedtuple('Information', ['city', 'state', 'pin_code'])

x = ('Pune', 'Maharashtra', 411027)
info1 = Information._make(x)
print(info1)

Output:

Information(city='Pune', state='Maharashtra', pin_code=411027)

6. _asdict() function

The _asdict() function helps creates an instance of OrderedDict from Namedtuple.

from collections import namedtuple

Information = namedtuple('Information', ['city', 'state', 'pin_code'])

x = ('Pune', 'Maharashtra', 411027)
info1 = Information._make(x)

ordered_output = info1._asdict()
print(ordered_output)

Output:

{'city': 'Pune', 'state': 'Maharashtra', 'pin_code': 411027}

7. _replace(**kwargs) function

Since namedtuple is immutable, the values cannot be altered. It returns a new instance by replacing the corresponding keys with a new set of values.

from collections import namedtuple

Information = namedtuple('Information', ['city', 'state', 'pin_code'])

x = ('Pune', 'Maharashtra', 411027)
info1 = Information._make(x)

info2 = info1._replace(city='Satara', state='Maharashtra', pin_code=411031)
print(info2)

Output:

Information(city='Satara', state='Maharashtra', pin_code=411031)

8. Namedtuple attributes

  • _fields: It provides information about the fields.
  • _fields_defaults: It provides information about the default values of the fields set by the user.

Example 1: _fields attribute

from collections import namedtuple

Information = namedtuple('Information', ['city', 'state', 'pin_code'])

print("Fields: ")
print (Information._fields)

Output:

Fields: 
('city', 'state', 'pin_code')

Example 2: _fields_defaults attribute

from collections import namedtuple

Information = namedtuple('Information', ['city', 'state', 'pin_code'], defaults=['Pune', 'Maharashtra'])

print("Default Fields: ")
print (Information._fields_defaults)

Output:’

Default Fields: 
{'state': 'Pune', 'pin_code': 'Maharashtra'}

9. “**” (double star) operator

This operator is used for the conversion of the dictionary to namedtuple.

from collections import namedtuple

Information = namedtuple('Information', ['city', 'state', 'pin_code'])

dict = { 'city' : "Pune", 'state':'Gujarat', 'pin_code' : '411027' }
print(Information(**dict))

Output:

Information(city='Pune', state='Gujarat', pin_code='411027')

Conclusion

Thus, in this article, we have understood the functionalities offered by Python’s collection Namedtuple object.


References

Leave a Reply

Your email address will not be published. Required fields are marked *