Registry / serialization / marshmallow-dataclass

marshmallow-dataclass

JSON →
library8.7.1pypypi✓ verified 25d ago

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-dataclass
INSTALL
IMPORT
SIG · MARSHMALLOW-DATACL
M
marshmallow-dataclass
serializationpythonv8.7.1
Install
2.0s avg
Import
572ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v8.7.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.580s · 19.3MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.0s · import 0.564s · 20MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

class_schema
from marshmallow_dataclass import class_schema
dataclass_json
from marshmallow_dataclass.decorators import dataclass_json
from marshmallow_dataclass import dataclass_json
The `dataclass_json` decorator was moved from the root module to `marshmallow_dataclass.decorators` in v8.0.0.

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
Debug
Known issues
breakingVersion 8.0.0 removed `union_field` and moved `dataclass_json`. It also bumped the minimum Python version requirement to 3.8+.
fix
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.
affects: >=8.0.0
breakingVersion 6.0.0 changed the signature of the `class_schema` function and discouraged the older `NewType` pattern for schema generation.
fix
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.
affects: >=6.0.0
gotchaMarshmallow `post_load` and `pre_load` methods must be defined on the *generated Marshmallow Schema*, not directly within the dataclass.
fix
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.
affects: All versions
gotchaDataclass `Optional` types (`Optional[str]`) automatically map to Marshmallow fields with `allow_none=True`. If `None` is not desired for an optional field, you must explicitly set `allow_none=False` via metadata.
fix
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})`.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'marshmallow-dataclass'
The 'marshmallow-dataclass' library is not installed in the Python environment.
fix
Install the library using pip: `pip install marshmallow-dataclass`
marshmallow.exceptions.ValidationError: {'_schema': ['Invalid input type. ']}
The `load` method of a `marshmallow-dataclass` generated schema received input that was not a dictionary, such as a JSON string, when it expected a dictionary.
fix
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()`.
ValueError: 'load_default' must not be set for required fields.
This error occurs when a Marshmallow field (implicitly or explicitly generated by `marshmallow-dataclass`) is marked as `required=True` but also has a default value (via `load_default` or `missing`), which are mutually exclusive concepts in Marshmallow's validation logic.
fix
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`.
TypeError: 'str' object is not callable
This error can occur when `from __future__ import annotations` is used, causing type hints to be stringified. `marshmallow-dataclass` might incorrectly process these stringified type hints as actual types or callable objects, leading to a `TypeError`.
fix
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.
Upgrade
Version history
8.7.1latest on PyPI · released Sep 12, 2024
Audit
Dependencies
marshmallowrequiredCore dependency for schema generation and data processing.
dataclasses-jsonoptionalRequired for the `dataclass_json` decorator functionality.
Agent activity
5 hits · last 30 days
node
4
Resources
marshmallow-dataclass — pip install marshmallow-dataclass · libregistry