androidengineers.Book a session

Python 08 · Objects and interfaces

Dataclasses, equality, and value objects

articleSelf-paced

Learn the concept

A dataclass reduces repetitive code for objects whose main purpose is storing named fields. It can generate initialization, representation, and equality behavior. Fields still need domain validation where appropriate; annotations alone are not runtime checks.

A frozen dataclass prevents normal field reassignment, but it does not make nested mutable objects deeply immutable. Prefer immutable field types when you need a value object with stable behavior. Equality usually compares fields rather than identity.

Use value objects for things such as an operation identifier or a validated configuration. Use explicit service objects when behavior depends on external systems. This distinction makes tests clearer: records can be compared by value, while adapters are exercised through their methods.

Run and inspect

from dataclasses import dataclass

@dataclass(frozen=True)
class Document:
    identifier: str
    tags: tuple[str, ...]

a = Document("d1", ("guide",))
b = Document("d1", ("guide",))
assert a == b
assert a is not b

Your exercise

Create a dataclass for a search result with ID, score, and source version. Validate scores separately and compare results by value.

Check your understanding

You can explain why frozen fields containing a list would still allow the list itself to change.

YOUR LEARNING JOURNEY

0 of 42 available lessons completed

Progress saved in this browser. No account needed.
Dataclasses, equality, and value objects | Python for AI Engineering | Android Engineers