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.
pip install marshmallow-dataclassVerified import paths — ran on the pinned version, not inferred.
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.
Use `marshmallow.fields.Union` directly instead of `union_field`. Import `dataclass_json` from `marshmallow_dataclass.decorators` if you still need it (though it's generally discouraged in favor of `class_schema`). Ensure your environment uses Python 3.8 or newer.
Always pass the dataclass directly to `class_schema(MyDataclass)` instead of `NewType('MySchema', MyDataclass)`. Review specific changes to `class_schema` parameters if you were using advanced configurations.Define `post_load` or `pre_load` methods as part of the `UserSchema` class (if you're inheriting and extending it) or by dynamically adding them after schema generation if needed. Do not try to add these directly to your `dataclass` definition.
For an optional field that should *not* allow `None` during deserialization (e.g., if it must be missing or a valid value, but not `None`), explicitly set `field(metadata={'allow_none': False})`.Install the library using pip: `pip install marshmallow-dataclass`
Ensure that the input passed to the `load` method is a dictionary. If you have a JSON string, parse it into a dictionary first using `json.loads()`.
If the field is truly required (must be present in input), remove any default values. If it has a default and should be optional, remove `required=True`. For fields that must be present but can accept `None`, use `Optional[Type]` and explicitly set `allow_none=True` in the `field`'s `metadata`.
Temporarily remove `from __future__ import annotations` from the module where the dataclass is defined to see if it resolves the issue. If it does, consider upgrading Python or `typing_extensions`, or refactor type hints to avoid forward references in a way that causes this conflict.