Python › Dataclasses & NamedTuples

How do you use dataclasses.field(compare=False) or field(repr=False) to exclude a specific field from the auto-generated __eq__ or __repr__?

Advanced

Answer

Pass compare=False to exclude a field from the auto-generated __eq__ (and ordering methods) comparison logic, or repr=False to exclude it from the auto-generated __repr__ output — useful for fields like an internal cache or a large binary blob that shouldn't affect equality or clutter the printed representation.
@dataclass
class User:
    name: str
    password_hash: str = field(repr=False)  # hidden from __repr__ for security
    last_login: str = field(compare=False, default="")  # doesn't affect equality checks

u = User("Sam", "hashed_value")
print(u)  # User(name='Sam', last_login='') -- password_hash omitted
Real-world example Excluding a sensitive field (like a password hash) from a dataclass's printed representation, or excluding a timestamp from equality comparisons.

Common follow-ups: How would you exclude a field from __init__ ENTIRELY as well, using field(init=False)?