mashumaro
mashumaro is a fast and well-tested serialization library built on top of Python dataclasses. It provides efficient conversion of dataclass instances to and from various formats like JSON, YAML, TOML, MessagePack, and plain dictionaries. It is actively maintained with frequent releases, currently at version 3.20.
Warnings
- breaking In v3.15, deserialization behavior for Unions with `int | float`, `str`, `bool`, and `NoneType` changed. Values are now passed through without coercion for numeric types (if they match), `str` is guaranteed a string version, `bool` uses standard truth testing, and `NoneType` is guaranteed `None`. This can lead to different deserialization results if your application relied on previous implicit coercions or conversions.
- breaking Support for Python 3.8 was dropped in mashumaro v3.15. Projects using Python 3.8 must pin mashumaro to a version prior to 3.15.
- gotcha When using `DataClassORJSONMixin`, prior to v3.13.1, the `to_json` method's type annotation incorrectly returned `str`. This was fixed in v3.13.1 to return `str` or `bytes` correctly depending on `orjson_options`, affecting static analysis and potentially runtime if strict type checks are in place.
- gotcha Mashumaro offers two primary approaches for serialization: Mixins (e.g., `DataClassJSONMixin`) for dataclass models, and Codecs (e.g., `JSONDecoder`, `JSONEncoder`) for converting arbitrary Python types or top-level collections. Choosing the wrong approach can lead to more verbose code or lack of desired functionality.
- gotcha The `forbid_extra_keys` configuration option (introduced in v3.13) and `Alias(...)` annotation for field aliasing (also v3.13) offer powerful control but can lead to deserialization failures if not configured correctly. Extra keys will be rejected if `forbid_extra_keys` is set to `True`, and fields might not deserialize by their original name if `Alias` is used without `allow_deserialization_not_by_alias`.
Install
-
pip install mashumaro -
pip install mashumaro[orjson]
Imports
- DataClassJSONMixin
from mashumaro.mixins.json import DataClassJSONMixin
- DataClassDictMixin
from mashumaro import DataClassDictMixin
- build_json_schema
from mashumaro.jsonschema import build_json_schema
Quickstart
from dataclasses import dataclass
from mashumaro.mixins.json import DataClassJSONMixin
@dataclass
class User(DataClassJSONMixin):
name: str
email: str
age: int
# Serialize to JSON
user = User(name='Alice', email='alice@example.com', age=30)
json_str = user.to_json()
print(f"Serialized: {json_str}")
# Deserialize from JSON
restored_user = User.from_json(json_str)
print(f"Deserialized: {restored_user}")
assert restored_user == user