If you are working with typing.NamedTuple definitions, you may use the extension NamedTupleSchema to generate your schema.

NamedTuple Type API

This extension modifies loading behavior to deserialize directly to instances of your defined NamedTuple:

from marshmallow_annotations import NamedTupleSchema
from typing import NamedTuple, Optional

class Vector(NamedTuple):
    x: int
    y: Optional[int]
    z: Optional[int] = 5

class VectorSchema(NamedTupleSchema):
    class Meta:
        target = Vector

schema = VectorSchema()
schema.load({'x': 1}).data

# Vector(x=1, y=None, z=5)

schema.dump(Vector(x=1, y=None, z=5)).data

# {'x': 1, 'y': None, 'z': 5}

Additionally, the Meta class provides you with the option flag dump_default_args to control whether attribute values matching defaults should be dumped or ignored; by default, matches are dumped:

class VectorSchemaDropDefaults(NamedTupleSchema):
    class Meta:
        target = Vector
        dump_default_args = False

schema = VectorSchemaDropDefaults()
schema.dump(Vector(x=1, y=None, z=5)).data

# {'x': 1}

NamedTuple Converter

class marshmallow_annotations.ext.namedtuple.NamedTupleConverter(*, registry: marshmallow_annotations.base.TypeRegistry = <marshmallow_annotations.registry.DefaultTypeRegistry object>) → None[source]

NamedTuple Schema

class marshmallow_annotations.ext.namedtuple.NamedTupleSchema(extra=None, only=None, exclude=(), prefix='', strict=None, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]

Derived class for creating typing.NamedTuple schema with automatic post-load conversion to namedtuple instances.

class marshmallow_annotations.ext.namedtuple.NamedTupleSchemaOpts(meta, *args, **kwargs)[source]

NamedTuple specific AnnotationSchemaOpts, additionally provides:

  • dump_default_fields