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.

Easy Python 3.9+ Aug 9, 2026 OOP & classes 15 views 0 copies

Python code

27 lines
Python 3.9+
class 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

stdout
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

  1. Use `dataclass` with a `from_dict` classmethod that uses `field(default=...)` for defaults.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.