How to Build a Class Method Alternative Constructor from Dict in Python
Use a classmethod alternative constructor to build a Book instance from a dictionary with sensible defaults.
Python code
27 linesclass Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
@classmethod
def from_dict(cls, data):
"""Alternative constructor that builds a Book from a dictionary."""
return cls(
title=data["title"],
author=data["author"],
pages=data.get("pages", 0)
)
def __repr__(self):
return f"Book('{self.title}', '{self.author}', {self.pages})"
if __name__ == "__main__":
book_data = {
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"pages": 180
}
book = Book.from_dict(book_data)
print(book)
Output
Book('The Great Gatsby', 'F. Scott Fitzgerald', 180)
How it works
The @classmethod decorator makes from_dict a method that receives the class itself as the first argument, not an instance. This allows it to call cls(...) to create a new instance, which is essential for alternative constructors in subclasses. The dictionary access uses data["title"] to require the field and data.get("pages", 0) to provide a default when the key is missing. Returning cls instead of hardcoding Book ensures inheritance works correctly. The __repr__ method provides a readable string representation, which makes the printed output clear and debugging easier.
Common mistakes
- Using `Book` directly instead of `cls` in the classmethod, which breaks inheritance.
- Forgetting to use `.get()` for optional fields, causing a KeyError.
- Not using `@classmethod` decorator, making the method an instance method instead.
- Passing a dictionary that is missing required keys without a clear error.
Variations
- Use `dataclass` with a `from_dict` classmethod that uses `field(default=...)` for defaults.
- Use a separate constructor function like `Book.create_from_api_response(data)` that maps and validates fields.
Real-world use cases
- Building ORM model instances from raw database query results in Python.
- Creating domain objects from API JSON payloads during ingestion in web services.
- Populating configuration data structures from environment variables stored as a dict.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.