Sub topic 1
The Boilerplate Problem with Plain Classes
Many Python classes exist only to hold a few values together: a point, a version number, a row from a file. Python lets you write such a class, but it makes you spell out the same mechanical code every time. This chapter shows that code, shows where it goes wrong, and explains why a generator for it is worth having. The rest of this tutorial covers the generator, which is @dataclass.
Prerequisites
This chapter assumes you can already:
- Define a class and create instances, including setting attributes in
__init__. - Read basic special methods:
__init__,__repr__and__eq__. - Read type annotation syntax such as
x: int. - Tell mutable objects (lists, dicts) from immutable ones (tuples, strings, numbers).
- Run Python 3.7 or newer. Later chapters use
slotsandkw_only, which need 3.10 or newer.
What a plain class gives you by default
Start with the smallest class that stores two values.
class Bare:
def __init__(self, x, y=0.0):
self.x = x
self.y = y
a = Bare(1.5)
b = Bare(1.5)
print(a) # <__main__.Bare object at 0x...> (the address varies)
print(a == b) # False
print(a == a) # TruePython gives Bare three behaviors that are rarely what you want for a data holder:
reprshows the class name and a memory address. Printing the object tells you nothing about its values, which makes debugging and logging harder.==compares identity. The inheritedobject.__eq__returnsTrueonly when both sides are the same object. Two instances holding identical values are unequal.- The object is hashable by identity.
hash(a)works, andacan be a dict key or set member, but two equal-looking instances are different keys.
To get the behavior you expect from a record, you write the missing methods yourself.
The hand-written version
Here is the same class with a readable repr and value-based equality.
class Point:
def __init__(self, x, y=0.0):
self.x = x
self.y = y
def __repr__(self):
return f"Point(x={self.x!r}, y={self.y!r})"
def __eq__(self, other):
if other.__class__ is not self.__class__:
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
p = Point(1.5)
print(p) # Point(x=1.5, y=0.0)
print(p == Point(1.5, 0.0)) # True
print(p == (1.5, 0.0)) # FalseThat is fifteen lines for two values. Each method has a separate job:
| Method | Job | What you must write |
|---|---|---|
| `__init__` | Store constructor arguments | Each field name as a parameter, again as `self.name = name` |
| `__repr__` | Readable text for debugging | Each field name inside a format string |
| `__eq__` | Value-based equality | Each field name inside a tuple, on both sides |
The returns of NotImplemented in __eq__ are deliberate. They tell Python to try the other operand's __eq__ and then fall back to identity. Returning False there, or letting an AttributeError escape when other is a different type, are both common mistakes.
The same name, written many times
Each field name appears in all three methods. For x in Point, that is five places: the __init__ parameter, the self.x assignment, the repr string, and both sides of the __eq__ tuple. A class with five fields has about twenty-five mentions. Nothing checks that these lists agree.
Failure mode: the forgotten field
Suppose you add a third coordinate to Point and update only some of the methods.
class Point3:
def __init__(self, x, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return f"Point3(x={self.x!r}, y={self.y!r}, z={self.z!r})"
def __eq__(self, other):
if other.__class__ is not self.__class__:
return NotImplemented
return (self.x, self.y) == (other.x, other.y) # z forgotten
print(Point3(1, 2, 3) == Point3(1, 2, 99)) # True, which is wrongNo error is raised. The repr shows the difference, but == hides it. A bug like this typically surfaces far from its cause, for example when a cache treats two different points as the same entry.
The reverse mistake is also easy: a typo in a repr string, or a field assigned in __init__ under a slightly different attribute name. Code review catches some of these. A tool that derives all the methods from one list of fields prevents the whole class of error.
Failure mode: defining `__eq__` removes hashing
There is a subtle rule here. If a class defines __eq__ and does not define __hash__, Python sets __hash__ to None. The class instances then become unhashable.
class Pt:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if other.__class__ is not self.__class__:
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
try:
hash(Pt(1, 2))
except TypeError as e:
print(e) # unhashable type: 'Pt'Python does this to protect you from breaking a core invariant: objects that compare equal must have equal hashes. The default identity hash would violate it once equality is by value. If you want to use Pt in a set or as a dict key, you must write __hash__ yourself, and it must use the same fields as __eq__.
class HashablePt(Pt):
def __hash__(self):
return hash((self.x, self.y))
print({HashablePt(1, 2): "ok"}) # works as a dict keyNow there is another list of fields to keep in sync. Hashing also only makes sense if the fields do not change after the object is used as a key, which a plain class does nothing to enforce.
Failure mode: ordering multiplies the code
Sorting records needs comparison methods. A full set is __lt__, __le__, __gt__ and __ge__. The standard library helps with functools.total_ordering, which fills in the rest when you supply __eq__ and one ordering method.
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, major, minor=0, patch=0):
self.major = major
self.minor = minor
self.patch = patch
def _key(self):
return (self.major, self.minor, self.patch)
def __repr__(self):
return f"Version({self.major!r}, {self.minor!r}, {self.patch!r})"
def __eq__(self, other):
if other.__class__ is not self.__class__:
return NotImplemented
return self._key() == other._key()
def __lt__(self, other):
if other.__class__ is not self.__class__:
return NotImplemented
return self._key() < other._key()
def __hash__(self):
return hash(self._key())
print(Version(1, 2) < Version(1, 10)) # True
print(sorted([Version(2), Version(1, 5), Version(1)]))This is about thirty lines, and it already introduces a helper (_key) whose only purpose is to reduce the repetition. Comparing tuples works because Python compares them element by element, left to right. Remember that detail, because generated comparison code relies on the same rule.
The key helper centralizes the field list for comparison and hashing, but __init__ and __repr__ still list the fields separately.
Why this matters beyond typing effort
The cost is not only keystrokes. Four consequences matter in real projects:
- The class's intent is buried. A reader scanning thirty lines to learn "this is a version with three integers" has to verify that every method agrees.
- Changes are risky. Adding or renaming a field means editing every method in step.
- Behavior differs between classes. One author returns
NotImplementedin__eq__, another returnsFalse, a third forgets__hash__. Inconsistent edge-case behavior makes a codebase harder to trust. - Mutable default arguments invite a separate trap. Writing
def __init__(self, items=[])shares one list among all instances. The fix is aNonesentinel and a check inside__init__, which is more boilerplate again.
class BasketOld:
def __init__(self, owner, items=None):
self.owner = owner
self.items = [] if items is None else itemsThe None sentinel prevents the sharing bug, but it also hides the fact that items is a list, and it makes None a value users could pass on purpose.
What the fix looks like
The methods above follow one pattern, so a program can generate them from a list of field names and types. That is the idea behind dataclasses, added in Python 3.7 by PEP 557. You declare fields with annotations and apply a decorator.
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float = 0.0
print(Point(1.5)) # Point(x=1.5, y=0.0)
print(Point(1.5) == Point(1.5)) # TrueThis produces an __init__, a __repr__ and an __eq__ equivalent to the hand-written ones. The field list is written once, so the "forgotten field" bug cannot occur. The next chapter explains exactly what the decorator generates and how to configure it. Later chapters cover ordering, hashing, immutability and mutable defaults, all of which this chapter showed as manual chores.
Summary of the problem
- A plain class inherits identity-based
==and an uninformativerepr. - Fixing both by hand repeats every field name in several methods.
- Nothing keeps those repetitions consistent, so fields get forgotten.
- Defining
__eq__silently disables hashing, so you must add a matching__hash__. - Ordering needs more methods or
functools.total_ordering. - Mutable defaults need a
Nonesentinel pattern.
Exercise
A teammate adds a field label to a hand-written class and updates __init__ and __repr__ but not __eq__. Two instances differ only in label. What does == return, and what does printing them show?
Show answer
== returns True, because __eq__ still compares only the old fields. Printing shows the two different labels, since __repr__ was updated. The class gives no error, so the inconsistency is easy to miss.
Exercise
You write a class with a custom __eq__ and no __hash__, then put an instance in a set. What happens, and why does Python behave this way?
Show answer
Python raises TypeError: unhashable type. When a class defines __eq__ without __hash__, Python sets __hash__ to None. The identity-based default hash would break the rule that equal objects must have equal hashes, so you must define __hash__ using the same fields as __eq__.
Exercise
Write the hand-written __eq__ for a class with fields name and age, so that comparing with an unrelated type does not raise an error and does not wrongly return False.
Show answer
def _eq(self, other): if other.class is not self.class_: return NotImplemented return (self.name, self.age) == (other.name, other.age)