marshmallow-dataclass

8.7.1 · active · verified Thu Apr 09

marshmallow-dataclass is a Python library that enables the seamless conversion of standard Python dataclasses into Marshmallow schemas. This simplifies data serialization, deserialization, and validation by automatically generating schemas based on dataclass definitions. As of version 8.7.1, it provides robust type hint support and integrates well with existing Marshmallow workflows. Releases are generally driven by new features, bug fixes, or compatibility updates with Marshmallow.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a dataclass, generate a Marshmallow schema using `class_schema`, and then use the generated schema to load (deserialize) data into a dataclass instance and dump (serialize) a dataclass instance back to a dictionary. It also shows how to use Marshmallow metadata fields like `required`, `load_only`, and `dump_only` within the dataclass `field` definition.

from dataclasses import dataclass, field
from datetime import datetime
from marshmallow_dataclass import class_schema

@dataclass
class User:
    id: int = field(metadata={'required': True})
    name: str
    email: str = field(metadata={'load_only': True})
    created_at: datetime = field(default_factory=datetime.now, metadata={'dump_only': True})

# Generate a Marshmallow schema from the dataclass
UserSchema = class_schema(User)

# Instantiate the schema
user_schema = UserSchema()

# Example data
user_data = {
    'id': 1,
    'name': 'Alice',
    'email': 'alice@example.com'
}

# Deserialize (load) data into a dataclass instance
try:
    user_obj = user_schema.load(user_data)
    print(f"Loaded User: {user_obj.name} (ID: {user_obj.id})")
    # 'email' is load_only, so not in user_obj after load by default if not passed in constructor
    print(f"User email (load_only): {user_data.get('email')}")
except Exception as e:
    print(f"Error loading data: {e}")

# Serialize (dump) a dataclass instance to a dictionary
dumped_data = user_schema.dump(user_obj)
print(f"Dumped data: {dumped_data}")
# 'email' is load_only, 'created_at' is dump_only
assert 'email' not in dumped_data
assert 'created_at' in dumped_data
assert dumped_data['id'] == 1

view raw JSON →