Make an immutable coordinate record with namedtuple

Make an immutable coordinate record with namedtuple

By Batu. AI assistance was used to prepare this article.

collections.namedtuple() creates a tuple subclass whose positions also have readable attribute names. Here, Coordinate has x and y fields. The resulting instances can be indexed, unpacked, compared as tuples, and accessed as point.x or point.y. Because the underlying structure is a tuple, assigning to a field raises AttributeError instead of altering the original coordinate.

from collections import namedtuple

Coordinate = namedtuple("Coordinate", ["x", "y"])
origin = Coordinate(2, 3)
moved = origin._replace(y=9)

try:
    origin.x = 5
except AttributeError:
    immutable = True
else:
    immutable = False

assert immutable is True
assert origin == Coordinate(2, 3)
assert moved == Coordinate(2, 9)
assert moved.x == 2 and moved[1] == 9

print(f"origin={origin}")
print(f"moved={moved}")
print(f"x={moved.x}")
print(f"immutable={immutable}")

Expected stdout

origin=Coordinate(x=2, y=3)
moved=Coordinate(x=2, y=9)
x=2
immutable=True

_replace(y=9) is the update mechanism shown here: it returns a new Coordinate, leaving origin at (2, 3). The printed representation includes field names, which is useful when inspecting a result. The assertions check this specific construction and update result, while the caught exception records the field-assignment behavior used by the recipe.

Immutability is shallow. A named tuple can hold a mutable object, such as a list, whose contents may still be changed. namedtuple() also does not enforce that x and y are numeric, share units, or lie in a permitted range; validate those constraints before construction when they matter. Field names must be valid identifiers and cannot begin with an underscore. For defaults or static type annotations, consider a dataclass or typing.NamedTuple when those features better fit the program.

Source: Python namedtuple() documentation.

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic