Dataclasses

Dataclasses are a Python feature for quickly defining classes that have reasonable constructors, comparison and equality functions, and pretty printers.

For example, we could create a Point class as follows. The field syntax is part of Python's new type annotation machinery. Fields should come after the docstring and before any methods. Fields are written as name : type, where type is a type hint.

from dataclasses import dataclass

@dataclass
class Point:
    """Points on the plane."""
    x: int
    y: int

print('Point has value equality? ', Point(3, 6) == Point(x=3, y=6))
print('Repr output: ', Point(3, 6))
Point has value equality?  True
Repr output:  Point(x=3, y=6)

We get a default constructor that lets us build points with = or {{{results(=)}}}. Comparison and equality are based on the values of x and y rather than the identity of the object. We can even make our class immutable (sort of) by using ==.

In comparison, we can look at the behavior of a standard Python class:

class StdPoint:
    def __init__(self, x, y):
	self.x = x
	self.y = y

print('StdPoint has value equality?', StdPoint(3, 6) == StdPoint(x=3, y=6))
print('Repr output: ', StdPoint(3, 6))
StdPoint has value equality? False
Repr output:  <__main__.StdPoint object at 0x7f4f2de893c0>

Last updated: 2023-03-07 Tue 20:30