marshmallow3-annotations

raw JSON →
1.1.0 verified Mon Apr 27 auth: no python

A library that allows using Python type annotations to define marshmallow 3 schemas, automatically generating Schema classes from annotated dataclasses or models. Version 1.1.0 supports dicts; release cadence is sporadic.

pip install marshmallow3-annotations
error ModuleNotFoundError: No module named 'marshmallow3_annotations'
cause Incorrect import path (maybe using hyphens or different casing).
fix
Install with: pip install marshmallow3-annotations. Then import: from marshmallow3_annotations import annotation_schema
error TypeError: annotation_schema() missing 1 required positional argument: 'cls'
cause Passing an instance instead of the class, or no argument.
fix
Call annotation_schema with the class itself: annotation_schema(MyClass)
error AttributeError: 'NoneType' object has no attribute 'fields'
cause annotation_schema returned None or the generated schema is empty because the dataclass has no annotated fields.
fix
Ensure the class is a dataclass with type-annotated fields (e.g., name: str).
gotcha annotation_schema expects a class, not an instance. Pass the class itself.
fix UserSchema = annotation_schema(User) # not User()
gotcha Only simple types like str, int, float, bool, list, dict are supported. Custom types or nested dataclasses may not work.
fix Use marshmallow fields directly for complex types, or define a nested schema manually.
deprecated The library may not be actively maintained; consider using marshmallow-dataclass or marshmallow-dataclass3 instead.
fix Migrate to marshmallow-dataclass (more features) or marshmallow-dataclass3 (Python 3.7+).

Decorate a dataclass with type annotations, then call annotation_schema to generate a marshmallow Schema.

from marshmallow import Schema, fields
from marshmallow3_annotations import annotation_schema
from dataclasses import dataclass

@dataclass
class User:
    name: str
    email: str

UserSchema = annotation_schema(User)
# Use UserSchema like any marshmallow Schema
schema = UserSchema()
result = schema.dump(User(name='John', email='john@example.com'))
print(result)  # {'name': 'John', 'email': 'john@example.com'}