Track a small product inventory using typed dataclass records.
What You Will Learn
Dataclasses make inventory records concise while normal functions and collections provide behavior. This example models quantities explicitly and updates a record using dataclasses.replace to avoid modifying the original record.
For concurrent stock operations use a database or another authoritative store.
Class interfaces should preserve their stated invariants. Type annotations describe intent but do not enforce runtime types on their own.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class InventoryProduct:
sku: str
quantity: int
original_product = InventoryProduct("P-100", 8)
updated_product = replace(original_product, quantity=original_product.quantity + 3)
print(original_product.quantity)
print(updated_product.quantity)
How the Example Works
- The imports provide the standard-library tools used in the demonstration: dataclasses.
- The class InventoryProduct groups data and behavior; its methods run when called on an instance.
- The variable original_product holds the result of InventoryProduct('P-100', 8). Later lines use that value or inspect how it changes.
- The variable updated_product holds the result of replace(original_product, quantity=original_product.quantity + 3). Later lines use that value or inspect how it changes.
Expected output from the example:
8
11
When You Would Use This
A class becomes useful when several operations must maintain rules around related data. Think about which state belongs to each instance, which operations should be public, and how errors should be reported. Avoid making the design more complex than the underlying task.
Practice: Modify the Code
Add a validated restock function that returns a new InventoryProduct.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming frozen dataclasses automatically validate nonnegative stock quantities.
- Overwriting a product record without tracking the reason for a stock change.
Key Takeaways
- Track a small product inventory using typed dataclass records.
- Dataclasses make inventory records concise while normal functions and collections provide behavior.
- For concurrent stock operations use a database or another authoritative store.