Modifying & Extending Named Tuples in Python
Named tuple returns instance of tuple class and tuples are immutable. But, while programming, we often require to modify item and add new item by extending existing tuples.
This article explains how to modify and extend existing named tuples using _replace()
and _fields
.
Consider we have following named tuples for 2D point:
from collections import namedtuple
Point2D = namedtuple('Point2D', 'x y')
pt = Point2D(10,20)
print("Point is: ", pt)
Output
Point is: Point2D(x=10, y=20)
Since namedtuple returns instance of standard tuple
, its value can not be changed like:
from collections import namedtuple
Point2D = namedtuple('Point2D', 'x y')
pt = Point2D(10,20)
pt.x = 100
Output
AttributeError: can't set attribute
So, to modify and extend existing named tuples we use _replace()
and _fields()
method. Remember these methods create another instance of namedtuple by modifying the existing one.
Modifying namedtuple Using _replace
Handy method to modify the existing value of some properties in namedtuple is _replace
. See example below:
from collections import namedtuple
Point2D = namedtuple('Point2D', 'x y')
pt = Point2D(x=10,y=20)
pt = pt._replace(x=100)
print("Modified point is: ", pt)
Output
Modified point is: Point2D(x=100, y=20)
Extending namedtuple Using _fields
Suppose we want to extend existing Point2D
having co-ordinates x, y to Point3D
having co-ordinates x, y, z then we can use _fields
method as follow:
from collections import namedtuple
Point2D = namedtuple('Point2D', 'x y')
pt = Point2D(x=10, y=20)
# extending namedtuple
Point3D = namedtuple('Point3D', Point2D._fields + ('z', ))
# extending existing point
pt = Point3D(*pt, z=500)
# result
print("Point3D details: ", Point3D._fields)
print("Extended point: ", pt)
Output
Point3D details: ('x', 'y', 'z') Extended point: Point3D(x=10, y=20, z=500)