### Install mashumaro Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/00-START-HERE.md Install the mashumaro library using pip. This is the first step to using its features. ```bash pip install mashumaro ``` -------------------------------- ### Install Mashumaro with YAML support Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-other-formats.md Install the necessary package to enable YAML serialization with Mashumaro. ```bash pip install mashumaro[yaml] ``` -------------------------------- ### Install mashumaro with MessagePack support Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-other-formats.md Install the mashumaro library with the MessagePack extra to enable MessagePack serialization. ```bash pip install mashumaro[msgpack] ``` -------------------------------- ### Install Mashumaro Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/quick-start.md Install the mashumaro library using pip. Optional dependencies for specific formats can be installed with extras. ```bash pip install mashumaro ``` ```bash pip install mashumaro[orjson] # High-performance JSON ``` ```bash pip install mashumaro[yaml] # YAML support ``` ```bash pip install mashumaro[toml] # TOML support ``` ```bash pip install mashumaro[msgpack] # MessagePack support ``` -------------------------------- ### Full Example: Airport and Flight Serialization Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/types.md Demonstrates a full example using SerializableType for Airport and integrating it into a DataClassDictMixin for Flight serialization and deserialization. ```python from dataclasses import dataclass from mashumaro import DataClassDictMixin from mashumaro.types import SerializableType class Airport(SerializableType): def __init__(self, code: str, city: str): self.code = code self.city = city def _serialize(self): return {"code": self.code, "city": self.city} @classmethod def _deserialize(cls, value): return cls(value["code"], value["city"]) @dataclass class Flight(DataClassDictMixin): origin: Airport destination: Airport flight = Flight.from_dict({ "origin": {"code": "JFK", "city": "New York"}, "destination": {"code": "LAX", "city": "Los Angeles"} }) ``` -------------------------------- ### DataClassORJSONMixin Installation and Import Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-json.md Instructions on how to install the orjson extra for mashumaro and import the DataClassORJSONMixin. ```APIDOC ## Installation ```bash pip install mashumaro[orjson] ``` ## Import ```python from mashumaro.mixins.orjson import DataClassORJSONMixin ``` ``` -------------------------------- ### Install DataClassTOMLMixin Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-other-formats.md Install mashumaro with TOML support using pip. This command installs the necessary packages for TOML serialization and deserialization. ```bash pip install mashumaro[toml] ``` -------------------------------- ### Running Mashumaro Benchmarks Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md Clone the repository, set up a virtual environment, install dependencies, and run the benchmark script to evaluate performance in your environment. ```bash git clone git@github.com:Fatal1ty/mashumaro.git cd mashumaro python3 -m venv env && source env/bin/activate pip install -e . pip install -r requirements-dev.txt ./benchmark/run.sh ``` -------------------------------- ### Example JSON Schema Definitions Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md This JSON output contains the schema definitions for User and Device objects. ```json { "User": { "type": "object", "title": "User", "properties": { "id": { "type": "string", "format": "uuid" }, "name": { "type": "string" } }, "additionalProperties": false, "required": [ "id", "name" ] }, "Device": { "type": "object", "title": "Device", "properties": { "id": { "type": "string", "format": "uuid" }, "model": { "type": "string" } }, "additionalProperties": false, "required": [ "id", "model" ] } } ``` -------------------------------- ### UnsupportedSerializationEngine Example Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/exceptions.md Demonstrates catching the UnsupportedSerializationEngine exception when an unknown serialization engine is specified in field metadata. This exception is raised during serialization. ```python from dataclasses import dataclass, field from mashumaro import DataClassDictMixin @dataclass class MyClass(DataClassDictMixin): x: int = field(metadata={"serialize": "unknown_engine"}) try: MyClass(x=1).to_dict() except UnsupportedSerializationEngine as e: print(f"Unsupported engine: {e.msg}") ``` -------------------------------- ### Example JSON Schema for Device List Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md This is the generated JSON schema for a list of Device objects. ```json { "type": "array", "items": { "$ref": "#/components/schemas/Device" } } ``` -------------------------------- ### Example: Conditional Serialization with Context Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/serialization-hooks.md This example demonstrates how to use the `context` argument in `__post_serialize__` to conditionally include sensitive data. The `ADD_SERIALIZATION_CONTEXT` option must be enabled in the `Config` class. ```python from dataclasses import dataclass from mashumaro import DataClassDictMixin from mashumaro.config import BaseConfig, ADD_SERIALIZATION_CONTEXT @dataclass class User(DataClassDictMixin): id: int name: str password: str class Config(BaseConfig): code_generation_options = [ADD_SERIALIZATION_CONTEXT] def __post_serialize__(self, d, context=None): # Only include password if context indicates trusted client if context and context.get('include_sensitive'): return d # Remove password for untrusted clients d.pop('password', None) return d user = User(id=1, name="Alice", password="secret") untrusted = user.to_dict() # No password trusted = user.to_dict(context={'include_sensitive': True}) # Includes password ``` -------------------------------- ### Example JSON Schema for User List Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md This is the generated JSON schema for a list of User objects. ```json { "type": "array", "items": { "$ref": "#/components/schemas/User" } } ``` -------------------------------- ### Install mashumaro with orjson support Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-json.md Install the mashumaro library with the orjson extra to enable JSON serialization using the orjson library. This is a prerequisite for using DataClassORJSONMixin. ```bash pip install mashumaro[orjson] ``` -------------------------------- ### Basic ISODateTimeStrategy Example Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/types.md Implement a custom strategy to serialize and deserialize datetime objects to/from ISO format strings. This strategy is applied using metadata in a dataclass field. ```python from dataclasses import dataclass, field from datetime import datetime from mashumaro import DataClassDictMixin, field_options from mashumaro.types import SerializationStrategy class ISODateTimeStrategy(SerializationStrategy): def serialize(self, value: datetime) -> str: return value.isoformat() def deserialize(self, value: str) -> datetime: return datetime.fromisoformat(value) @dataclass class Event(DataClassDictMixin): name: str timestamp: datetime = field( metadata=field_options( serialization_strategy=ISODateTimeStrategy() ) ) ``` -------------------------------- ### Example: Container with GenericSerializableType Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/types.md Example of a generic Container class implementing GenericSerializableType to handle type parameters during serialization and deserialization. ```python from typing import Generic, TypeVar, Type T = TypeVar('T') class Container(Generic[T], GenericSerializableType): def __init__(self, items: list[T]): self.items = items def _serialize(self, types: list[Type]) -> list: # types[0] would be the T type return self.items @classmethod def _deserialize(cls, value: list, types: list[Type]) -> 'Container': return cls(value) ``` -------------------------------- ### Example: Field-Based Discrimination with Discriminator Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/types.md Demonstrates using Discriminator with a 'field' parameter to deserialize a union of Cat and Dog types based on a 'type' field. ```python from dataclasses import dataclass from typing import Annotated, Type from mashumaro import DataClassDictMixin from mashumaro.types import Discriminator @dataclass class Cat(DataClassDictMixin): type: str = "cat" meow_volume: int @dataclass class Dog(DataClassDictMixin): type: str = "dog" bark_pitch: int AnimalUnion = Annotated[ Cat | Dog, Discriminator(field="type", include_subtypes=True) ] @dataclass class Zoo(DataClassDictMixin): animals: list[AnimalUnion] zoo = Zoo.from_dict({ "animals": [ {"type": "cat", "meow_volume": 5}, {"type": "dog", "bark_pitch": 440} ] }) ``` -------------------------------- ### Global Serialization Strategy Configuration Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/types.md Configure a serialization strategy globally within a dataclass's Config. This example sets a default strategy for all datetime fields. ```python from dataclasses import dataclass from datetime import datetime from mashumaro import DataClassDictMixin from mashumaro.config import BaseConfig # Assuming ISODateTimeStrategy is defined elsewhere # class ISODateTimeStrategy(SerializationStrategy): # def serialize(self, value: datetime) -> str: # return value.isoformat() # def deserialize(self, value: str) -> datetime: # return datetime.fromisoformat(value) @dataclass class MyClass(DataClassDictMixin): dt: datetime class Config(BaseConfig): serialization_strategy = { datetime: ISODateTimeStrategy(), } ``` -------------------------------- ### Example: Using a Tagger Function with Discriminator Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/types.md Shows how to use Discriminator with a variant_tagger_fn to dynamically determine the type tag based on the class name. ```python from typing import Annotated, Type from mashumaro.types import Discriminator # Assuming Cat and Dog are defined as in the previous example # Cat | Dog is the union type to be discriminated AnimalUnion = Annotated[ Cat | Dog, Discriminator( variant_tagger_fn=lambda cls: cls.__name__, include_subtypes=True ) ] ``` -------------------------------- ### Comprehensive Data Class Configuration with Custom Strategy Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/configuration.md Define a User data class with aliasing, omitting null values, and a custom serialization strategy for datetime objects. This example demonstrates advanced configuration using field_options and BaseConfig. ```python from dataclasses import dataclass, field from datetime import datetime from typing import Optional from mashumaro import DataClassDictMixin, field_options from mashumaro.config import BaseConfig, TO_DICT_ADD_OMIT_NONE_FLAG from mashumaro.types import SerializationStrategy class CustomDateTimeStrategy(SerializationStrategy): def serialize(self, value: datetime) -> str: return value.strftime("%Y-%m-%d %H:%M:%S") def deserialize(self, value: str) -> datetime: return datetime.strptime(value, "%Y-%m-%d %H:%M:%S") @dataclass class User(DataClassDictMixin): user_id: int = field(metadata=field_options(alias="id")) user_name: str = field(metadata=field_options(alias="name")) created_at: datetime email: Optional[str] = None class Config(BaseConfig): serialize_by_alias = True omit_none = True code_generation_options = [TO_DICT_ADD_OMIT_NONE_FLAG] serialization_strategy = { datetime: CustomDateTimeStrategy() } aliases = { "user_id": "id", "user_name": "name" } ``` -------------------------------- ### ORJSONDecoder Example Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/codecs.md Instantiate ORJSONDecoder for a specific type and decode JSON bytes into a Python object. Ensure the input data is valid JSON. ```python from mashumaro.codecs.orjson import ORJSONDecoder decoder = ORJSONDecoder(list[int]) result = decoder.decode(b'[1, 2, 3]') # Result: [1, 2, 3] ``` -------------------------------- ### Class-Level Discriminator Setup Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md Define a class-level discriminator for automatic subclass handling during deserialization. Ensure `include_subtypes=True` is set. ```python from dataclasses import dataclass from ipaddress import IPv4Address from typing import List from mashumaro import DataClassDictMixin from mashumaro.config import BaseConfig from mashumaro.types import Discriminator @dataclass class ClientEvent(DataClassDictMixin): class Config(BaseConfig): discriminator = Discriminator( # <- add discriminator field="type", include_subtypes=True, ) @dataclass class ClientConnectedEvent(ClientEvent): type = "connected" client_ip: IPv4Address @dataclass class ClientDisconnectedEvent(ClientEvent): type = "disconnected" client_ip: IPv4Address @dataclass class AggregatedEvents(DataClassDictMixin): list: List[ClientEvent] # <- use base class here ``` -------------------------------- ### Generic Serialization Strategy for List Types Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md Shows how to define a generic serialization strategy for all list types by registering a method for the list's origin type. This example converts all elements in lists of integers and floats to strings during serialization. ```python from dataclasses import dataclass from mashumaro import DataClassDictMixin @dataclass class C(DataClassDictMixin): ints: list[int] floats: list[float] class Config: serialization_strategy = { list: { # origin type for list[int] and list[float] is list "serialize": lambda x: list(map(str, x)), } } assert C([1], [2.2]).to_dict() == {'ints': ['1'], 'floats': ['2.2']} ``` -------------------------------- ### Configure orjson Encoder Options Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md Customize the default options for `orjson.dumps` when using `DataClassORJSONMixin`. This example shows how to enable `orjson.OPT_NON_STR_KEYS` to handle non-string dictionary keys. ```python import orjson from dataclasses import dataclass from typing import Dict from mashumaro.config import BaseConfig from mashumaro.mixins.orjson import DataClassORJSONMixin @dataclass class MyClass(DataClassORJSONMixin): x: Dict[int, int] class Config(BaseConfig): orjson_options = orjson.OPT_NON_STR_KEYS assert MyClass({1: 2}).to_json() == {"1": 2} ``` -------------------------------- ### Handle Missing Third-Party Modules with ThirdPartyModuleNotFoundError Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/exceptions.md Catch this exception when a required third-party module for a mashumaro mixin is not installed. It provides the name of the missing module and the field/class that requires it. ```python try: from mashumaro.mixins.yaml import DataClassYAMLMixin except ThirdPartyModuleNotFoundError as e: print(f"Install {e.module_name} to use YAML") ``` -------------------------------- ### Strategy Pattern for Datetime Serialization Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/types.md Implement a strategy pattern for handling different data formats, specifically for datetime objects. This example uses UnixTimestampStrategy to serialize and deserialize datetime objects to and from Unix timestamps. Configure this strategy within the inner 'Config' class of your dataclass. ```python from dataclasses import dataclass from datetime import datetime from mashumaro import DataClassDictMixin from mashumaro.config import BaseConfig from mashumaro.types import SerializationStrategy class UnixTimestampStrategy(SerializationStrategy): def serialize(self, value: datetime) -> float: return value.timestamp() def deserialize(self, value: float) -> datetime: return datetime.fromtimestamp(value) @dataclass class Event(DataClassDictMixin): name: str timestamp: datetime class Config(BaseConfig): serialization_strategy = { datetime: UnixTimestampStrategy() } ``` -------------------------------- ### DataClassMessagePackMixin Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-other-formats.md Provides MessagePack binary serialization and deserialization for dataclasses. Install with `pip install mashumaro[msgpack]` and import from `mashumaro.mixins.msgpack`. ```APIDOC ## DataClassMessagePackMixin Provides MessagePack binary serialization. ### Installation ```bash pip install mashumaro[msgpack] ``` ### Import ```python from mashumaro.mixins.msgpack import DataClassMessagePackMixin ``` ### Instance Methods #### to_msgpack ```python @final def to_msgpack( self: T, encoder: Encoder = default_encoder, **to_dict_kwargs: Any ) -> bytes ``` Serialize the dataclass to MessagePack bytes. | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | encoder | Callable | msgpack.packb | Custom encoder function | | to_dict_kwargs | Any | optional | Keyword arguments passed to `to_dict()` | **Returns:** MessagePack-encoded bytes. **Example:** ```python from dataclasses import dataclass from mashumaro.mixins.msgpack import DataClassMessagePackMixin @dataclass class Message(DataClassMessagePackMixin): id: int content: str binary_data: bytes msg = Message(id=1, content="Hello", binary_data=b"data") packed = msg.to_msgpack() ``` ### Class Methods #### from_msgpack ```python @classmethod @final def from_msgpack( cls: Type[T], data: bytes, decoder: Decoder = default_decoder, **from_dict_kwargs: Any ) -> T ``` Deserialize MessagePack data into a dataclass instance. | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | data | bytes | required | MessagePack-encoded data | | decoder | Callable | msgpack.unpackb | Custom decoder function | | from_dict_kwargs | Any | optional | Keyword arguments passed to `from_dict()` | **Returns:** An instance of the dataclass. **Example:** ```python msg = Message.from_msgpack(packed) ``` ### Special Type Handling The `MessagePackDialect` provides native handling for: - `bytes`: Passed directly without conversion - `bytearray`: Converted from bytes on deserialization ``` -------------------------------- ### Serialize and Deserialize Portfolio to/from JSON Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md Demonstrates creating a `Portfolio` instance, serializing it to JSON using `to_json()`, and deserializing it back using `from_json()`. Asserts that the deserialized object is equal to the original. ```python portfolio = Portfolio( currencies=[ CurrencyPosition(Currency.USD, 238.67), CurrencyPosition(Currency.EUR, 361.84), ], stocks=[ StockPosition("AAPL", "Apple", 10), StockPosition("AMZN", "Amazon", 10), ] ) portfolio_json = portfolio.to_json() assert Portfolio.from_json(portfolio_json) == portfolio ``` -------------------------------- ### Implementing Pre- and Post- Hooks Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/README.md Shows how to implement `__pre_deserialize__` to modify incoming data before deserialization (e.g., lowercasing email) and `__post_serialize__` to add extra fields to the serialized output (e.g., a version number). ```python @dataclass class User(DataClassDictMixin): name: str email: str @classmethod def __pre_deserialize__(cls, d): d['email'] = d['email'].lower() return d def __post_serialize__(self, d): d['_version'] = "1.0" return d ``` -------------------------------- ### Configuration Files with TOML Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/00-START-HERE.md Use `DataClassTOMLMixin` to load configuration from TOML files directly into data classes. Ensure the TOML file is read as a string. ```python from dataclasses import dataclass @dataclass class DatabaseConfig(DataClassTOMLMixin): host: str port: int username: str config = DatabaseConfig.from_toml(open("config.toml").read()) ``` -------------------------------- ### Deserialize with String Engine Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md Use 'pendulum' engine for datetime deserialization. Ensure the 'pendulum' library is installed. ```python from datetime import datetime from dataclasses import dataclass, field from mashumaro import DataClassDictMixin @dataclass class A(DataClassDictMixin): x: datetime = field( metadata={"deserialize": "pendulum"} ) ``` -------------------------------- ### Custom Serialization Strategy for Datetime and Date Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md Illustrates registering custom serialization and deserialization methods for datetime and date types using a dictionary in the Config class. It shows how to use a custom class for datetime and a dictionary with specific functions for date. ```python from dataclasses import dataclass from datetime import datetime, date from mashumaro import DataClassDictMixin from mashumaro.config import BaseConfig from mashumaro.types import SerializationStrategy class FormattedDateTime(SerializationStrategy): def __init__(self, fmt): self.fmt = fmt def serialize(self, value: datetime) -> str: return value.strftime(self.fmt) def deserialize(self, value: str) -> datetime: return datetime.strptime(value, self.fmt) @dataclass class DataClass(DataClassDictMixin): x: datetime y: date class Config(BaseConfig): serialization_strategy = { datetime: FormattedDateTime("%Y"), date: { # you can use specific str values for datetime here as well "deserialize": "pendulum", "serialize": date.isoformat, }, } instance = DataClass.from_dict({"x": "2021", "y": "2021"}) # DataClass(x=datetime.datetime(2021, 1, 1, 0, 0), y=Date(2021, 1, 1)) dictionary = instance.to_dict() # {'x': '2021', 'y': '2021-01-01'} ``` -------------------------------- ### Get Collected Type Definitions Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/jsonschema.md Retrieve all type definitions that have been collected by the `JSONSchemaBuilder`. The definitions can then be serialized to JSON. ```python definitions = builder.get_definitions() print(definitions.to_json()) ``` -------------------------------- ### Import TOML Codecs Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/codecs.md Import the TOMLDecoder and TOMLEncoder classes from mashumaro.codecs.toml. ```python from mashumaro.codecs.toml import TOMLDecoder, TOMLEncoder ``` -------------------------------- ### __post_serialize__ Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-dict.md This instance method is called after serialization is complete. It allows you to modify the resulting dictionary, for example, by adding extra fields. ```APIDOC ## __post_serialize__ ### Description Called after serialization completes. Allows modification of the serialized dictionary. ### Method `def __post_serialize__(self: T, d: dict[Any, Any]) -> dict[Any, Any]` ### Returns The modified dictionary. ### Example ```python @dataclass class User(DataClassDictMixin): id: int name: str def __post_serialize__(self, d): # Add a timestamp after serialization d['_serialized_at'] = '2023-01-01T00:00:00' return d ``` ``` -------------------------------- ### Python Dataclass with __post_serialize__ Hook Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-dict.md Use __post_serialize__ to modify the serialized dictionary after serialization. This example adds a '_serialized_at' timestamp. ```python from dataclasses import dataclass from mashumaro.mixins import DataClassDictMixin @dataclass class User(DataClassDictMixin): id: int name: str def __post_serialize__(self, d): # Add a timestamp after serialization d['_serialized_at'] = '2023-01-01T00:00:00' return d ``` -------------------------------- ### Import MessagePack Codecs Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/codecs.md Import the MessagePackDecoder and MessagePackEncoder classes from mashumaro.codecs.msgpack. ```python from mashumaro.codecs.msgpack import MessagePackDecoder, MessagePackEncoder ``` -------------------------------- ### SerializableType with Annotations Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/types.md Enable automatic nested type conversion by setting use_annotations=True on the class. This example shows a Point class with annotations. ```python class Point(SerializableType, use_annotations=True): def __init__(self, x: float, y: float): self.x = x self.y = y def _serialize(self) -> list[float]: return [self.x, self.y] @classmethod def _deserialize(cls, value: list[float]) -> 'Point': return cls(*value) ``` -------------------------------- ### Python Dataclass with __pre_serialize__ Hook Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-dict.md Use __pre_serialize__ to modify the instance before serialization. This example returns the instance itself, implying no modification is needed. ```python from dataclasses import dataclass from mashumaro.mixins import DataClassDictMixin @dataclass class User(DataClassDictMixin): id: int name: str def __pre_serialize__(self): # Return a modified copy for serialization return self ``` -------------------------------- ### Configuration File Loading Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/quick-start.md Load configuration from TOML files into dataclasses using DataClassTOMLMixin. This simplifies managing application settings. ```python from dataclasses import dataclass from mashumaro.mixins.toml import DataClassTOMLMixin @dataclass class DatabaseConfig(DataClassTOMLMixin): host: str port: int username: str password: str # Load from file import toml config_dict = toml.load("config.toml") db_config = DatabaseConfig.from_dict(config_dict["database"]) ``` -------------------------------- ### Import JSON Schema Builder and Utilities Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/jsonschema.md Import necessary components for JSON Schema generation from Mashumaro. ```python from mashumaro.jsonschema import ( JSONSchemaBuilder, build_json_schema, DRAFT_2020_12, OPEN_API_3_1, ) ``` -------------------------------- ### Python Dataclass with __post_deserialize__ Hook Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-dict.md Use __post_deserialize__ to modify the deserialized instance. This example ensures the 'name' field is title-cased after deserialization. ```python from dataclasses import dataclass from mashumaro.mixins import DataClassDictMixin @dataclass class User(DataClassDictMixin): id: int name: str @classmethod def __post_deserialize__(cls, obj): # Ensure name is title-cased after deserialization obj.name = obj.name.title() return obj ``` -------------------------------- ### Python Dataclass with __pre_deserialize__ Hook Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-dict.md Use __pre_deserialize__ to modify input data before deserialization. This example converts the 'name' field to lowercase. ```python from dataclasses import dataclass from mashumaro.mixins import DataClassDictMixin @dataclass class User(DataClassDictMixin): id: int name: str @classmethod def __pre_deserialize__(cls, d): # Convert name to lowercase before processing if 'name' in d: d['name'] = d['name'].lower() return d ``` -------------------------------- ### Import Basic Codecs Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/API-INDEX.md Import the BasicDecoder, BasicEncoder, and general decode/encode functions for fundamental data handling. ```python from mashumaro.codecs.basic import BasicDecoder, BasicEncoder, decode, encode ``` -------------------------------- ### ORJSONEncoder Example Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/codecs.md Instantiate ORJSONEncoder for a specific type and encode a Python object into JSON bytes. The encoder is designed for efficient JSON serialization. ```python from mashumaro.codecs.orjson import ORJSONEncoder encoder = ORJSONEncoder(list[int]) result = encoder.encode([1, 2, 3]) # Result: b'[1,2,3]' ``` -------------------------------- ### Import ORJSON Codecs Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/codecs.md Import the ORJSONDecoder and ORJSONEncoder classes from the mashumaro.codecs.orjson module. ```python from mashumaro.codecs.orjson import ORJSONDecoder, ORJSONEncoder ``` -------------------------------- ### Basic DataClassDictMixin Usage Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/README.md Demonstrates basic deserialization from a dictionary and serialization back to a dictionary using `DataClassDictMixin`. Ensure `dataclasses` and `mashumaro` are imported. ```python from dataclasses import dataclass from mashumaro import DataClassDictMixin @dataclass class User(DataClassDictMixin): id: int name: str email: str user = User.from_dict({"id": 1, "name": "Alice", "email": "alice@example.com"}) user_dict = user.to_dict() ``` -------------------------------- ### Integrate DataClassJSONMixin for JSON Serialization Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md Inherit from `DataClassJSONMixin` to add JSON serialization and deserialization capabilities to your dataclasses. This example shows how to integrate it into a `Portfolio` dataclass. ```python from mashumumaro.mixins.json import DataClassJSONMixin @dataclass class Portfolio(DataClassJSONMixin): currencies: list[CurrencyPosition] stocks: list[StockPosition] ``` -------------------------------- ### Mashumaro v2 `from_*` Method Signature Source: https://github.com/fatal1ty/mashumaro/blob/master/docs/2to3.md Illustrates the signature of `from_json`, `from_msgpack`, and `from_yaml` methods in mashumaro version 2. ```python @classmethod def from_*( # where * is json, msgpack, yaml cls, data: EncodedData, decoder: Decoder = ..., dict_params: Mapping = {}, **decoder_kwargs, ) ``` -------------------------------- ### Implement _serialize Method Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/types.md Implement the _serialize method to convert an instance into a basic serializable form like a list of floats. ```python class Point(SerializableType): def __init__(self, x: float, y: float): self.x = x self.y = y def _serialize(self) -> list[float]: return [self.x, self.y] ``` -------------------------------- ### Import MessagePack Codecs Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/API-INDEX.md Import MessagePack decoder, encoder, and convenience functions for MessagePack data. ```python from mashumaro.codecs.msgpack import ( MessagePackDecoder, MessagePackEncoder, msgpack_decode, msgpack_encode ) ``` -------------------------------- ### Use Alias for Field Renaming Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/types.md Use Annotated with Alias to rename fields during serialization and deserialization. The example shows mapping 'id' to 'user_id' and 'name' to 'user_name'. ```python from mashumaro.types import Alias from typing import Annotated from mashumaro import DataClassDictMixin from dataclasses import dataclass @dataclass class User(DataClassDictMixin): user_id: Annotated[int, Alias("id")] user_name: Annotated[str, Alias("name")] user = User.from_dict({"id": 1, "name": "Alice"}) # Result: User(user_id=1, user_name='Alice') user.to_dict() # Result: {'user_id': 1, 'user_name': 'Alice'} # Use config option serialize_by_alias=True to serialize with aliases ``` -------------------------------- ### Performance Comparison: NewType vs. Direct Value Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md Compares the performance of creating instances of a NewType versus using the base type directly. Creating NewType instances incurs overhead when done manually, but not when using mashumaro's from_* methods or decoders. ```shell python -m timeit -s "from typing import NewType; MyInt = NewType('MyInt', int)" "MyInt(42)" ``` ```shell python -m timeit -s "from typing import NewType; MyInt = NewType('MyInt', int)" "42" ``` -------------------------------- ### Import BasicDecoder and BasicEncoder Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/codecs.md Import the BasicDecoder and BasicEncoder classes from the mashumaro.codecs.basic module or directly from mashumaro.codecs. ```python from mashumaro.codecs.basic import BasicDecoder, BasicEncoder # or from mashumaro.codecs import BasicDecoder, BasicEncoder ``` -------------------------------- ### Define Field Aliases for Serialization Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/configuration.md Use the `aliases` option to map different names for fields during serialization and deserialization. This example maps `user_id` to `id` and `user_name` to `name`. ```python from dataclasses import dataclass from mashumaro import DataClassDictMixin from mashumaro.config import BaseConfig @dataclass class User(DataClassDictMixin): user_id: int user_name: str class Config(BaseConfig): aliases = { "user_id": "id", "user_name": "name" } user = User.from_dict({"id": 1, "name": "Alice"}) ``` -------------------------------- ### Use RoundedDecimal for Decimal Serialization Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/types.md Apply RoundedDecimal in field metadata to control the precision and rounding of decimal values during serialization. This example rounds to 2 decimal places. ```python from dataclasses import dataclass, field from decimal import Decimal from mashumaro import DataClassDictMixin, field_options from mashumaro.types import RoundedDecimal @dataclass class Price(DataClassDictMixin): amount: Decimal = field( metadata=field_options( serialization_strategy=RoundedDecimal(places=2) ) ) price = Price(amount=Decimal("19.999")) price.to_dict() # Result: {'amount': '20.00'} ``` -------------------------------- ### Create JSONSchemaBuilder Instance Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/API-INDEX.md Instantiate JSONSchemaBuilder to programmatically build JSON schemas. Configure the builder with a specific dialect and optional reference prefix or plugins. ```python from mashumaro.jsonschema import JSONSchemaBuilder, DRAFT_2020_12, OPEN_API_3_1 builder = JSONSchemaBuilder( dialect: JSONSchemaDialect = DRAFT_2020_12, all_refs: bool | None = None, ref_prefix: str | None = None, plugins: Sequence[BasePlugin] = (), ) builder.build(instance_type: Type) -> JSONSchema builder.get_definitions() -> JSONSchemaDefinitions ``` -------------------------------- ### Import DataClassTOMLMixin Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-other-formats.md Import the DataClassTOMLMixin from the mashumaro library to enable TOML handling for your dataclasses. ```python from mashumaro.mixins.toml import DataClassTOMLMixin ``` -------------------------------- ### Basic Schema Generation from Dataclass Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/jsonschema.md Generate a JSON schema from a Python dataclass using `build_json_schema`. This example demonstrates generating a schema for a `Person` object with nested `Address`. ```python from dataclasses import dataclass from mashumaro.jsonschema import build_json_schema @dataclass class Address: street: str city: str zip_code: str @dataclass class Person: name: str age: int address: Address schema = build_json_schema(Person) print(schema.to_json()) ``` -------------------------------- ### Define and Deserialize Nested Dataclasses Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/quick-start.md Use `DataClassDictMixin` to enable dictionary conversion for nested dataclasses. This example shows how to deserialize a dictionary into a `Person` object which contains an `Address` object. ```python from dataclasses import dataclass from mashumaro import DataClassDictMixin @dataclass class Address(DataClassDictMixin): street: str city: str country: str @dataclass class Person(DataClassDictMixin): name: str age: int address: Address person = Person.from_dict({ "name": "Alice", "age": 30, "address": { "street": "123 Main St", "city": "New York", "country": "USA" } }) ``` -------------------------------- ### Import YAML Codecs Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/codecs.md Import the YAMLDecoder and YAMLEncoder classes from the mashumaro.codecs.yaml module. ```python from mashumaro.codecs.yaml import YAMLDecoder, YAMLEncoder ``` -------------------------------- ### BasicEncoder Initialization and Usage Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/codecs.md Initialize BasicEncoder with the type of the object to be encoded. Use the encode method to serialize an object into a serializable format. This example demonstrates encoding a Point object. ```python from mashumaro.codecs.basic import BasicEncoder # Assuming Point dataclass is defined as in the BasicDecoder example # @dataclass # class Point: # x: int # y: int encoder = BasicEncoder(Point) data = encoder.encode(Point(x=1, y=2)) # Result: {"x": 1, "y": 2} ``` -------------------------------- ### JSON Codec - Working with Third-Party Types Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/codecs.md Demonstrates how to use JSONDecoder and JSONEncoder to handle specific types, such as `datetime`, by providing the target type during initialization. ```APIDOC ## JSON Codec - Working with Third-Party Types ### Description This section illustrates how to configure JSON codecs to correctly handle complex or third-party types like `datetime`. By specifying the target type when creating the decoder or encoder, mashumaro can manage the serialization and deserialization of these types. ### Usage 1. **Initialize Decoder/Encoder**: Create an instance of `JSONDecoder` or `JSONEncoder`, passing the desired type (e.g., `list[datetime]`) to the constructor. 2. **Decode/Encode**: Use the `decode` or `encode` methods of the created instance. ### Example ```python from mashumaro.codecs.json import JSONDecoder, JSONEncoder from datetime import datetime # Create a decoder for a list of datetime objects date_decoder = JSONDecoder(list[datetime]) dates = date_decoder.decode('["2023-01-01T00:00:00", "2023-01-02T00:00:00"]') # Create an encoder for a list of datetime objects date_encoder = JSONEncoder(list[datetime]) encoded = date_encoder.encode(dates) ``` ``` -------------------------------- ### Import DataClassJSONMixin Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-json.md Import the DataClassJSONMixin for standard JSON serialization. ```python from mashumaro.mixins.json import DataClassJSONMixin ``` -------------------------------- ### Data Pipeline Processing Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/quick-start.md Process data through a pipeline involving reading JSON, transforming it, and writing to a different format like YAML. This example shows decoding from JSON and encoding to YAML. ```python # Read JSON, transform, write to different format data = JSONDecoder(User).decode(json_string) # Process... YAMLEncoder(User).encode(data) ``` -------------------------------- ### JSON Codec - Working with Custom Dialects Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/codecs.md Explains how to customize the behavior of JSON codecs by defining and using custom dialects, such as one that enables serialization by alias. ```APIDOC ## JSON Codec - Working with Custom Dialects ### Description This section details how to customize the encoding and decoding behavior of the JSON codec by implementing and applying custom dialects. A custom dialect allows you to modify specific aspects of the serialization process, such as controlling whether fields are serialized using their aliases. ### Usage 1. **Define Custom Dialect**: Create a class that inherits from `mashumaro.dialect.Dialect` and override desired attributes (e.g., `serialize_by_alias = True`). 2. **Apply Dialect**: Pass an instance of your custom dialect to the `default_dialect` parameter when initializing `JSONDecoder` or `JSONEncoder`. ### Example ```python from mashumaro.codecs.json import JSONDecoder from mashumaro.dialect import Dialect from datetime import date # Define a custom dialect that serializes fields by their aliases class CustomDialect(Dialect): serialize_by_alias = True # Initialize a decoder with the custom dialect decoder = JSONDecoder(list[date], default_dialect=CustomDialect) dates = decoder.decode('["2023-01-01", "2023-01-02"]') ``` ``` -------------------------------- ### Generating Schemas for API Documentation Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/jsonschema.md Generate JSON schemas for API request and response objects, which can then be integrated into OpenAPI specifications. This example shows schema generation for `APIRequest` and `APIResponse` dataclasses. ```python from dataclasses import dataclass from datetime import datetime from mashumaro.jsonschema import build_json_schema @dataclass class APIRequest: user_id: int action: str timestamp: datetime @dataclass class APIResponse: status: str data: dict timestamp: datetime request_schema = build_json_schema(APIRequest) response_schema = build_json_schema(APIResponse) # Use in OpenAPI documentation openapi_spec = { "components": { "schemas": { "APIRequest": request_schema.to_dict(), "APIResponse": response_schema.to_dict(), } } } ``` -------------------------------- ### Import TOML Codecs Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/API-INDEX.md Import specific TOML decoder, encoder, and convenience functions for TOML data handling. ```python from mashumaro.codecs.toml import TOMLDecoder, TOMLEncoder, toml_decode, toml_encode ``` -------------------------------- ### BasicDecoder Initialization and Usage Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/codecs.md Initialize BasicDecoder with a target shape type. Use the decode method to convert data into the specified type. This example shows decoding a single object and a list of objects. ```python from mashumaro.codecs.basic import BasicDecoder from dataclasses import dataclass @dataclass class Point: x: int y: int decoder = BasicDecoder(Point) point = decoder.decode({"x": 1, "y": 2}) # Result: Point(x=1, y=2) # Decode a list of points list_decoder = BasicDecoder(list[Point]) points = list_decoder.decode([{"x": 1, "y": 2}, {"x": 3, "y": 4}]) ``` -------------------------------- ### Import DataClassDictMixin Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-dict.md Import the DataClassDictMixin class from the mashumaro library. This is the base class for dictionary serialization. ```python from mashumaro import DataClassDictMixin ``` ```python from mashumaro.mixins.dict import DataClassDictMixin ``` -------------------------------- ### Build JSON Schema for List of Devices Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md Generates an OpenAPI 3.1 schema for a list of Device objects. Ensure Device dataclass is defined. ```python from mashumaro.jsonschema import JSONSchemaBuilder, OPEN_API_3_1 builder = JSONSchemaBuilder(OPEN_API_3_1) @dataclass class Device: id: UUID model: str print(builder.build(List[Device]).to_json()) ``` -------------------------------- ### Import BaseConfig Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/configuration.md Import the BaseConfig class to configure dataclass serialization behavior. ```python from mashumaro.config import BaseConfig ``` -------------------------------- ### Generate JSON Schema for Pydantic Models Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md Create a custom PydanticSchemaPlugin to integrate Pydantic models into mashumaro's JSON schema generation. This plugin converts Pydantic's model_json_schema into a mashumaro JSONSchema object. It requires Pydantic to be installed. ```python from dataclasses import dataclass from pydantic import BaseModel from mashumaro.jsonschema import build_json_schema from mashumaro.jsonschema.models import Context, JSONSchema from mashumaro.jsonschema.plugins import BasePlugin from mashumaro.jsonschema.schema import Instance class PydanticSchemaPlugin(BasePlugin): def get_schema( self, instance: Instance, ctx: Context, schema: JSONSchema | None = None, ) -> JSONSchema | None: try: if issubclass(instance.type, BaseModel): pydantic_schema = instance.type.model_json_schema() return JSONSchema.from_dict(pydantic_schema) except TypeError: return None class MyPydanticClass(BaseModel): x: int @dataclass class MyDataClass: y: MyPydanticClass schema = build_json_schema(MyDataClass, plugins=[PydanticSchemaPlugin()]) print(schema.to_json()) ``` -------------------------------- ### Basic Codec - One-Time Encoding/Decoding Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/codecs.md Demonstrates the use of the module-level `decode` and `encode` functions from the `mashumaro.codecs.basic` module for straightforward, one-off data transformations. ```APIDOC ## Basic Codec - One-Time Encoding/Decoding ### Description This example shows how to use the general-purpose `decode` and `encode` functions provided by the `mashumaro.codecs.basic` module. These functions are suitable for simple, one-time data conversion tasks where you don't need to configure a specific codec or reuse an instance. ### Usage Import the `decode` and `encode` functions directly from `mashumaro.codecs.basic` and call them with the data and the target type. ### Example ```python from mashumaro.codecs.basic import decode, encode # Decode a dictionary into a tuple of integers result = decode({"x": 1, "y": 2}, tuple[int, int]) # Encode a tuple of integers encoded = encode((1, 2), tuple[int, int]) ``` ``` -------------------------------- ### Import SerializationStrategy Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/types.md Import the base SerializationStrategy class from mashumaro.types. ```python from mashumaro.types import SerializationStrategy ``` -------------------------------- ### Import DataClassYAMLMixin Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-other-formats.md Import the DataClassYAMLMixin to add YAML serialization capabilities to your dataclasses. ```python from mashumaro.mixins.yaml import DataClassYAMLMixin ``` -------------------------------- ### Prepare Data Before Serialization Source: https://github.com/fatal1ty/mashumaro/blob/master/README.md Implement the __pre_serialize__ method to perform actions on the object instance just before it is serialized. This can be used for logging or modifying state. ```python from dataclasses import dataclass, field, ClassVar from mashumaro import DataClassJSONMixin @dataclass class A(DataClassJSONMixin): abc: int counter: ClassVar[int] = 0 def __pre_serialize__(self) -> 'A': self.counter += 1 return self obj = A(abc=123) obj.to_dict() obj.to_json() print(obj.counter) # 2 ``` -------------------------------- ### Custom Type Handling with SerializationStrategy Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/README.md Illustrates how to define a custom `SerializationStrategy` for handling specific types like `datetime`. This involves creating a class that implements `serialize` and `deserialize` methods and configuring it in the `Config` class. ```python from mashumaro.types import SerializationStrategy from datetime import datetime class DateTimeStrategy(SerializationStrategy): def serialize(self, value: datetime) -> str: return value.isoformat() def deserialize(self, value: str) -> datetime: return datetime.fromisoformat(value) @dataclass class Event(DataClassDictMixin): name: str timestamp: datetime class Config: serialization_strategy = { datetime: DateTimeStrategy() } ``` -------------------------------- ### Import JSON Codecs Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/codecs.md Import the necessary JSONDecoder and JSONEncoder classes from Mashumaro. ```python from mashumaro.codecs.json import JSONDecoder, JSONEncoder ``` -------------------------------- ### Import DataClassMessagePackMixin Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/mixins-other-formats.md Import the DataClassMessagePackMixin to add MessagePack capabilities to your dataclasses. ```python from mashumaro.mixins.msgpack import DataClassMessagePackMixin ``` -------------------------------- ### Import Discriminator Source: https://github.com/fatal1ty/mashumaro/blob/master/_autodocs/types.md Import the Discriminator class from mashumaro.types. ```python from mashumaro.types import Discriminator ```