marshmallow_annotations API

Warning

Scary looking type signatures a head.

Type API

This section will hopeful ease some of the stress and tension that will inevitably arise from looking at the following type signatures. Seriously, they’re not pretty.

Field Factory

A field factory is not the field’s instance constructor, rather it is any callable that accepts:

  1. An AbstractConverter instance
  2. A tuple of type hints
  3. A dictionary of configuration values for the underlying field

And returns a fully instantiated marshmallow Field instance, for example:

from marshmallow import List as ListField

def sequence_converter(converter, subtypes, opts):
    return ListField(converter.convet(subtypes[0]), **opts)

This might be registered against Tuple:

registry.register(typing.Tuple, sequence_converter)

A method that accepts a field factory contains the following signature:

Callable[[AbstractConverter, Tuple[type], Dict[str, Any]], FieldABC]

Registry

class marshmallow_annotations.base.TypeRegistry[source]

Abstraction representation of a registry mapping Python types to marshmallow field types.

This abstract class is provided primarily for type hinting purposes but also allows implementations outside of the default implementation in this library.

field_factory(target: type) → Callable[Callable[[marshmallow_annotations.base.AbstractConverter, Tuple[type], Dict[str, Any]], marshmallow.base.FieldABC], Callable[[marshmallow_annotations.base.AbstractConverter, Tuple[type], Dict[str, Any]], marshmallow.base.FieldABC]][source]

Decorator form of register:

@register.field_factor(bytes)
def custom(converter, subtypes, opts):
    return fields.Raw(**opts)

Returns the original function so it can be used again if needed.

abstractmethod get(target: type) → Callable[[marshmallow_annotations.base.AbstractConverter, Tuple[type], Dict[str, Any]], marshmallow.base.FieldABC][source]

Retrieves a field factory from the registry. If it doesn’t exist, this may raise a AnnotationConversionError:

registry.get(str)  # string field factory
registry.get(object)  # raises AnnotationConversionError
abstractmethod has(target: type) → bool[source]

Allows safely checking if a type has a companion field mapped already:

registry.has(int)     # True
registry.has(object)  # False

May also be used with in:

int in registry     # True
object in registry  # False
abstractmethod register(target: type, constructor: Callable[[marshmallow_annotations.base.AbstractConverter, Tuple[type], Dict[str, Any]], marshmallow.base.FieldABC]) → None[source]

Registers a raw field factory for the specified type:

from marshmallow import fields

def custom(converter, subtypes, opts):
    return fields.Raw(**opts)

registry.register(bytes, custom)
abstractmethod register_field_for_type(target: type, field: marshmallow.base.FieldABC) → None[source]

Registers a raw marshmallow field to be associated with a type:

from typing import NewType
Email = NewType("Email", str)

registry.register_field_for_type(Email, EmailField)
abstractmethod register_scheme_factory(target: type, scheme_or_name: Union[str, marshmallow.base.SchemaABC]) → None[source]

Registers an existing scheme or scheme name to be associated with a type:

from myapp.schema import ArtistScheme
from myapp.entities import Artist

registry.register_scheme_factory(Artist, ArtistScheme)
class marshmallow_annotations.registry.DefaultTypeRegistry(registry: Dict[type, Callable[[marshmallow_annotations.base.AbstractConverter, Tuple[type], Dict[str, Any]], marshmallow.base.FieldABC]] = None) → None[source]

Default implementation of TypeRegistry.

Provides default mappings of:

  • bool -> fields.Boolean
  • date -> fields.Date
  • datetime -> fields.DateTime
  • Decimal -> fields.Decimal
  • float -> fields.Float
  • int -> fields.Integer
  • str -> fields.String
  • time -> fields.Time
  • timedelta -> fields.TimeDelta
  • UUID -> fields.UUID
  • dict -> fields.Dict
  • typing.Dict -> fields.Dict

As well as a special factory for typing.List[T] that will generate either fields.List or fields.Nested

marshmallow_annotations.registry.field_factory(field: marshmallow.base.FieldABC) → Callable[[marshmallow_annotations.base.AbstractConverter, Tuple[type], Dict[str, Any]], marshmallow.base.FieldABC][source]

Maps a marshmallow field into a field factory

marshmallow_annotations.registry.scheme_factory(scheme_name: str) → Callable[[marshmallow_annotations.base.AbstractConverter, Tuple[type], Dict[str, Any]], marshmallow.base.FieldABC][source]

Maps a scheme or scheme name into a field factory

Converter

class marshmallow_annotations.base.AbstractConverter[source]

Converters handle gathering type hints and consulting with a TypeRegistry in order to produce marshmallow field instances:

from marshmallow_annotations import BaseConverter

converter = BaseConverter(registry)
converter.convert(int, {"required": False})
# marshmallow.fields.Integer(...)

This abstract class is provided primarily for type hinting purposes but also allows implementations outside of the default implementation in this library.

abstractmethod convert(typehint: type, opts: Union[typing.Dict[str, typing.Any], NoneType] = None, *, field_name: str = None, target: type = None) → marshmallow.base.FieldABC[source]

Used to convert a type hint into a FieldABC instance.

Versionchanged:2.2.0 Added field_name and target optional keyword only arguments
abstractmethod convert_all(target: type, ignore: AbstractSet[str] = frozenset(), configs: Union[typing.Dict[str, typing.Union[typing.Dict[str, typing.Any], NoneType]], NoneType] = None) → Dict[str, marshmallow.base.FieldABC][source]

Used to transform a type with annotations into a dictionary mapping the type’s attribute names to FieldABC instances.

abstractmethod is_scheme(typehint: type) → bool[source]

Used to check if the typehint passed if associated to a scheme or a regular field constructor.

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

Default implementation of AbstractConverter.

Handles parsing types for type hints and mapping those type hints into marshmallow field instances by way of a TypeRegistry instance.

Versionchanged:2.1.0 Added non-public hook _get_field_defaults
Versionchanged:2.2.0 Added non-public hooks _preprocess_typehint and _postprocess_typehint
_get_field_defaults(item)[source]

Non-public hookpoint to read default values for all fields from the target

_postprocess_typehint(typehint, kwargs, field_name, target)[source]

Non-public hookpoint for any postprocessing of typehint parsing for a given field.

_preprocess_typehint(typehint, kwargs, field_name, target)[source]

Non-public hookpoint for any preprocessing of typehint parsing for a given field

Schema

class marshmallow_annotations.scheme.AnnotationSchemaMeta(name, bases, attrs)[source]

Metaclass that handles produces the AnnotationSchema class. Provided for integration into other libraries and toolkits

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

Base class for creating annotation schema with:

from marshmallow_annotations import AnnotationSchema
from my.app.entities import Artist

class ArtistScheme(AnnotationSchema):
    class Meta:
        target = Artist
        register_as_scheme = True
class marshmallow_annotations.scheme.AnnotationSchemaOpts(meta, schema=None)[source]

marshmallow-annotations specific SchemaOpts implementation, provides:

  • converter_factory
  • registry
  • register_as_scheme
  • target
  • field_configs
  • converter

Exceptions

class marshmallow_annotations.exceptions.MarshmallowAnnotationError[source]
class marshmallow_annotations.exceptions.AnnotationConversionError[source]