Maintain consistency between equality and hash values.
How It Works
Hashable objects can serve as dict keys or set members. Equal objects must have equal hashes; making an equality-comparable mutable object hashable can break dictionary invariants if its hash-related state changes.
Defining __eq__ in a normal class typically disables the inherited __hash__ unless explicitly restored.
Step-by-Step Example
from dataclasses import dataclass
@dataclass(frozen=True)
class ProductCode:
code: str
first_code = ProductCode("A10")
second_code = ProductCode("A10")
print(first_code == second_code)
print(hash(first_code) == hash(second_code))
Understanding the Example
- The expression 'True)' supplies the value stored as '@dataclass(frozen'. This value is then used or checked by the later statements.
- The class groups related state and methods so each instance can manage its own values.
A successful run of this example prints the following output:
True
True
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Use two equal frozen dataclass instances as one dictionary key.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Returning different hashes for two objects considered equal by __eq__().
- Mutating an attribute used in a hash while the object is stored in a set.
Key Takeaways
- Maintain consistency between equality and hash values.
- Hashable objects can serve as dict keys or set members.
- Defining __eq__ in a normal class typically disables the inherited __hash__ unless explicitly restored.