Fields

Field classes for various types of data.

Classes:

AwareDateTime([format, default_timezone])

A formatted aware datetime string.

Bool

alias of Boolean

Boolean(*[, truthy, falsy])

A boolean field.

Constant(constant, **kwargs)

A field that (de)serializes to a preset constant.

Date([format])

ISO8601-formatted date string.

DateTime([format])

A formatted datetime string.

Decimal([places, rounding, allow_nan, as_string])

A field that (de)serializes to the Python decimal.Decimal type.

Dict([keys, values])

A dict field.

Email(*args, **kwargs)

An email field.

Enum(enum, *[, by_value])

An Enum field (de)serializing enum members by symbol (name) or by value.

Field(*, load_default, missing, ...)

Basic field from which other fields should extend.

Float(*[, allow_nan, as_string])

A double as an IEEE-754 double precision string.

Function([serialize, deserialize])

A field that takes the value returned by a function.

IP(*args[, exploded])

A IP address field.

IPInterface(*args[, exploded])

A IPInterface field.

IPv4(*args[, exploded])

A IPv4 address field.

IPv4Interface(*args[, exploded])

A IPv4 Network Interface field.

IPv6(*args[, exploded])

A IPv6 address field.

IPv6Interface(*args[, exploded])

A IPv6 Network Interface field.

Int

alias of Integer

Integer(*[, strict])

An integer field.

List(cls_or_instance, **kwargs)

A list field, composed with another Field class or instance.

Mapping([keys, values])

An abstract class for objects with key-value pairs.

Method([serialize, deserialize])

A field that takes the value returned by a Schema method.

NaiveDateTime([format, timezone])

A formatted naive datetime string.

Nested(nested, ...)

Allows you to nest a Schema inside a field.

Number(*[, as_string])

Base class for number fields.

Pluck(nested, field_name, **kwargs)

Allows you to replace nested data with one of the data's fields.

Raw(*, load_default, missing, dump_default, ...)

Field that applies no formatting.

Str

alias of String

String(*, load_default, missing, ...)

A string field.

Time([format])

A formatted time string.

TimeDelta(precision, serialization_type, ...)

A field that (de)serializes a datetime.timedelta object to an integer or float and vice versa.

Tuple(tuple_fields, *args, **kwargs)

A tuple field, composed of a fixed number of other Field classes or instances

URL

alias of Url

UUID(*, load_default, missing, dump_default, ...)

A UUID field.

Url(*[, relative, absolute, schemes, ...])

An URL field.

class marshmallow.fields.AwareDateTime(format: str | None = None, *, default_timezone: tzinfo | None = None, **kwargs)[source]

A formatted aware datetime string.

Parameters:
  • format – See DateTime.

  • default_timezone – Used on deserialization. If None, naive datetimes are rejected. If not None, naive datetimes are set this timezone.

  • kwargs – The same keyword arguments that Field receives.

New in version 3.0.0rc9.

Methods:

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_deserialize(value, attr, data, **kwargs) datetime[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

marshmallow.fields.Bool

alias of Boolean Methods:

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

Attributes:

default_error_messages

Default error messages.

falsy

Default falsy values.

truthy

Default truthy values.

class marshmallow.fields.Boolean(*, truthy: set | None = None, falsy: set | None = None, **kwargs)[source]

A boolean field.

Parameters:

Methods:

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

Attributes:

default_error_messages

Default error messages.

falsy

Default falsy values.

truthy

Default truthy values.

_deserialize(value, attr, data, **kwargs)[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_serialize(value, attr, obj, **kwargs)[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

default_error_messages = {'invalid': 'Not a valid boolean.'}

Default error messages.

falsy = {'0', 'F', 'FALSE', 'False', 'N', 'NO', 'No', 'OFF', 'Off', 'f', 'false', 'n', 'no', 'off', 0}

Default falsy values.

truthy = {'1', 'ON', 'On', 'T', 'TRUE', 'True', 'Y', 'YES', 'Yes', 'on', 't', 'true', 'y', 'yes', 1}

Default truthy values.

class marshmallow.fields.Constant(constant: Any, **kwargs)[source]

A field that (de)serializes to a preset constant. If you only want the constant added for serialization or deserialization, you should use dump_only=True or load_only=True respectively.

Parameters:

constant – The constant to return for the field attribute.

New in version 2.0.0.

Methods:

_deserialize(value, *args, **kwargs)

Deserialize value.

_serialize(value, *args, **kwargs)

Serializes value to a basic Python datatype.

_deserialize(value, *args, **kwargs)[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_serialize(value, *args, **kwargs)[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

class marshmallow.fields.Date(format: str | None = None, **kwargs)[source]

ISO8601-formatted date string.

Parameters:
  • format – Either "iso" (for ISO8601) or a date format string. If None, defaults to “iso”.

  • kwargs – The same keyword arguments that Field receives.

Attributes:

default_error_messages

Default error messages.

default_error_messages = {'format': '"{input}" cannot be formatted as a date.', 'invalid': 'Not a valid date.'}

Default error messages.

class marshmallow.fields.DateTime(format: str | None = None, **kwargs)[source]

A formatted datetime string.

Example: '2014-12-22T03:12:58.019077+00:00'

Parameters:
  • format – Either "rfc" (for RFC822), "iso" (for ISO8601), "timestamp", "timestamp_ms" (for a POSIX timestamp) or a date format string. If None, defaults to “iso”.

  • kwargs – The same keyword arguments that Field receives.

Changed in version 3.0.0rc9: Does not modify timezone information on (de)serialization.

Changed in version 3.19: Add timestamp as a format.

Methods:

_bind_to_schema(field_name, schema)

Update field with values from its parent schema.

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

Attributes:

default_error_messages

Default error messages.

_bind_to_schema(field_name, schema)[source]

Update field with values from its parent schema. Called by Schema._bind_field.

Parameters:
  • field_name (str) – Field name set in schema.

  • schema (Schema|Field) – Parent object.

_deserialize(value, attr, data, **kwargs) datetime[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_serialize(value, attr, obj, **kwargs) str | float | None[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

default_error_messages = {'format': '"{input}" cannot be formatted as a {obj_type}.', 'invalid': 'Not a valid {obj_type}.', 'invalid_awareness': 'Not a valid {awareness} {obj_type}.'}

Default error messages.

class marshmallow.fields.Decimal(places: int | None = None, rounding: str | None = None, *, allow_nan: bool = False, as_string: bool = False, **kwargs)[source]

A field that (de)serializes to the Python decimal.Decimal type. It’s safe to use when dealing with money values, percentages, ratios or other numbers where precision is critical.

Warning

This field serializes to a decimal.Decimal object by default. If you need to render your data as JSON, keep in mind that the json module from the standard library does not encode decimal.Decimal. Therefore, you must use a JSON library that can handle decimals, such as simplejson, or serialize to a string by passing as_string=True.

Warning

If a JSON float value is passed to this field for deserialization it will first be cast to its corresponding string value before being deserialized to a decimal.Decimal object. The default __str__ implementation of the built-in Python float type may apply a destructive transformation upon its input data and therefore cannot be relied upon to preserve precision. To avoid this, you can instead pass a JSON string to be deserialized directly.

Parameters:
  • places – How many decimal places to quantize the value. If None, does not quantize the value.

  • rounding – How to round the value during quantize, for example decimal.ROUND_UP. If None, uses the rounding value from the current thread’s context.

  • allow_nan – If True, NaN, Infinity and -Infinity are allowed, even though they are illegal according to the JSON specification.

  • as_string – If True, serialize to a string instead of a Python decimal.Decimal type.

  • kwargs – The same keyword arguments that Number receives.

New in version 1.2.0.

Methods:

_format_num(value)

Return the number value for value, given this field's num_type.

_validated(value)

Format the value or raise a ValidationError if an error occurs.

Attributes:

default_error_messages

Default error messages.

Classes:

num_type

alias of Decimal

_format_num(value)[source]

Return the number value for value, given this field’s num_type.

_validated(value)[source]

Format the value or raise a ValidationError if an error occurs.

default_error_messages = {'special': 'Special numeric values (nan or infinity) are not permitted.'}

Default error messages.

num_type

alias of Decimal Methods:

adjusted()

Return the adjusted exponent of the number.

as_integer_ratio()

Return a pair of integers, whose ratio is exactly equal to the original Decimal and with a positive denominator.

as_tuple()

Return a tuple representation of the number.

canonical()

Return the canonical encoding of the argument.

compare(other[, context])

Compare self to other.

compare_signal(other[, context])

Identical to compare, except that all NaNs signal.

compare_total(other[, context])

Compare two operands using their abstract representation rather than their numerical value.

compare_total_mag(other[, context])

Compare two operands using their abstract representation rather than their value as in compare_total(), but ignoring the sign of each operand.

conjugate()

Return self.

copy_abs()

Return the absolute value of the argument.

copy_negate()

Return the negation of the argument.

copy_sign(other[, context])

Return a copy of the first operand with the sign set to be the same as the sign of the second operand.

exp([context])

Return the value of the (natural) exponential function e**x at the given number.

fma(other, third[, context])

Fused multiply-add.

from_float()

Class method that converts a float to a decimal number, exactly.

is_canonical()

Return True if the argument is canonical and False otherwise.

is_finite()

Return True if the argument is a finite number, and False if the argument is infinite or a NaN.

is_infinite()

Return True if the argument is either positive or negative infinity and False otherwise.

is_nan()

Return True if the argument is a (quiet or signaling) NaN and False otherwise.

is_normal([context])

Return True if the argument is a normal finite non-zero number with an adjusted exponent greater than or equal to Emin.

is_qnan()

Return True if the argument is a quiet NaN, and False otherwise.

is_signed()

Return True if the argument has a negative sign and False otherwise.

is_snan()

Return True if the argument is a signaling NaN and False otherwise.

is_subnormal([context])

Return True if the argument is subnormal, and False otherwise.

is_zero()

Return True if the argument is a (positive or negative) zero and False otherwise.

ln([context])

Return the natural (base e) logarithm of the operand.

log10([context])

Return the base ten logarithm of the operand.

logb([context])

For a non-zero number, return the adjusted exponent of the operand as a Decimal instance.

logical_and(other[, context])

Return the digit-wise 'and' of the two (logical) operands.

logical_invert([context])

Return the digit-wise inversion of the (logical) operand.

logical_or(other[, context])

Return the digit-wise 'or' of the two (logical) operands.

logical_xor(other[, context])

Return the digit-wise 'exclusive or' of the two (logical) operands.

max(other[, context])

Maximum of self and other.

max_mag(other[, context])

Similar to the max() method, but the comparison is done using the absolute values of the operands.

min(other[, context])

Minimum of self and other.

min_mag(other[, context])

Similar to the min() method, but the comparison is done using the absolute values of the operands.

next_minus([context])

Return the largest number representable in the given context (or in the current default context if no context is given) that is smaller than the given operand.

next_plus([context])

Return the smallest number representable in the given context (or in the current default context if no context is given) that is larger than the given operand.

next_toward(other[, context])

If the two operands are unequal, return the number closest to the first operand in the direction of the second operand.

normalize([context])

Normalize the number by stripping the rightmost trailing zeros and converting any result equal to Decimal('0') to Decimal('0e0').

number_class([context])

Return a string describing the class of the operand.

quantize(exp[, rounding, context])

Return a value equal to the first operand after rounding and having the exponent of the second operand.

radix()

Return Decimal(10), the radix (base) in which the Decimal class does all its arithmetic.

remainder_near(other[, context])

Return the remainder from dividing self by other.

rotate(other[, context])

Return the result of rotating the digits of the first operand by an amount specified by the second operand.

same_quantum(other[, context])

Test whether self and other have the same exponent or whether both are NaN.

scaleb(other[, context])

Return the first operand with the exponent adjusted the second.

shift(other[, context])

Return the result of shifting the digits of the first operand by an amount specified by the second operand.

sqrt([context])

Return the square root of the argument to full precision.

to_eng_string([context])

Convert to an engineering-type string.

to_integral([rounding, context])

Identical to the to_integral_value() method.

to_integral_exact([rounding, context])

Round to the nearest integer, signaling Inexact or Rounded as appropriate if rounding occurs.

to_integral_value([rounding, context])

Round to the nearest integer without signaling Inexact or Rounded.

class marshmallow.fields.Dict(keys: Field | type | None = None, values: Field | type | None = None, **kwargs)[source]

A dict field. Supports dicts and dict-like objects. Extends Mapping with dict as the mapping_type.

Example:

numbers = fields.Dict(keys=fields.Str(), values=fields.Float())
Parameters:

kwargs – The same keyword arguments that Mapping receives.

New in version 2.1.0.

Classes:

mapping_type

alias of dict

mapping_type

alias of dict Methods:

clear()

copy()

fromkeys([value])

Create a new dictionary with keys from iterable and values set to value.

get(key[, default])

Return the value for key if key is in the dictionary, else default.

items()

keys()

pop(k[,d])

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem()

Remove and return a (key, value) pair as a 2-tuple.

setdefault(key[, default])

Insert key with a value of default if key is not in the dictionary.

update([E, ]**F)

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values()

class marshmallow.fields.Email(*args, **kwargs)[source]

An email field.

Parameters:
  • args – The same positional arguments that String receives.

  • kwargs – The same keyword arguments that String receives.

Attributes:

default_error_messages

Default error messages.

default_error_messages = {'invalid': 'Not a valid email address.'}

Default error messages.

class marshmallow.fields.Enum(enum: type[Enum], *, by_value: bool | Field | type = False, **kwargs)[source]

An Enum field (de)serializing enum members by symbol (name) or by value.

Parameters:
  • Enum (enum) – Enum class

  • by_value (boolean|Schema|Field) – Whether to (de)serialize by value or by name, or Field class or instance to use to (de)serialize by value. Defaults to False.

If by_value is False (default), enum members are (de)serialized by symbol (name). If it is True, they are (de)serialized by value using Field. If it is a field instance or class, they are (de)serialized by value using this field.

New in version 3.18.0.

Methods:

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

Attributes:

default_error_messages

Default error messages for various kinds of errors.

_deserialize(value, attr, data, **kwargs)[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_serialize(value, attr, obj, **kwargs)[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

default_error_messages = {'unknown': 'Must be one of: {choices}.'}

Default error messages for various kinds of errors. The keys in this dictionary are passed to Field.make_error. The values are error messages passed to marshmallow.exceptions.ValidationError.

class marshmallow.fields.Field(*, load_default: ~typing.Any = <marshmallow.missing>, missing: ~typing.Any = <marshmallow.missing>, dump_default: ~typing.Any = <marshmallow.missing>, default: ~typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: None | ~typing.Callable[[~typing.Any], ~typing.Any] | ~typing.Iterable[~typing.Callable[[~typing.Any], ~typing.Any]] = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str] | None = None, metadata: ~typing.Mapping[str, ~typing.Any] | None = None, **additional_metadata)[source]

Basic field from which other fields should extend. It applies no formatting by default, and should only be used in cases where data does not need to be formatted before being serialized or deserialized. On error, the name of the field will be returned.

Parameters:
  • dump_default – If set, this value will be used during serialization if the input value is missing. If not set, the field will be excluded from the serialized output if the input value is missing. May be a value or a callable.

  • load_default – Default deserialization value for the field if the field is not found in the input data. May be a value or a callable.

  • data_key – The name of the dict key in the external representation, i.e. the input of load and the output of dump. If None, the key will match the name of the field.

  • attribute – The name of the key/attribute in the internal representation, i.e. the output of load and the input of dump. If None, the key/attribute will match the name of the field. Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute, or using keys/attributes that are invalid variable names, unsuitable for field names. In most cases, you should use data_key instead.

  • validate – Validator or collection of validators that are called during deserialization. Validator takes a field’s input value as its only parameter and returns a boolean. If it returns False, an ValidationError is raised.

  • required – Raise a ValidationError if the field value is not supplied during deserialization.

  • allow_none – Set this to True if None should be considered a valid value during validation/deserialization. If load_default=None and allow_none is unset, will default to True. Otherwise, the default is False.

  • load_only – If True skip this field during serialization, otherwise its value will be present in the serialized data.

  • dump_only – If True skip this field during deserialization, otherwise its value will be present in the deserialized object. In the context of an HTTP API, this effectively marks the field as “read-only”.

  • error_messages (dict) – Overrides for Field.default_error_messages.

  • metadata – Extra information to be stored as field metadata.

Changed in version 2.0.0: Removed error parameter. Use error_messages instead.

Changed in version 2.0.0: Added allow_none parameter, which makes validation/deserialization of None consistent across fields.

Changed in version 2.0.0: Added load_only and dump_only parameters, which allow field skipping during the (de)serialization process.

Changed in version 2.0.0: Added missing parameter, which indicates the value for a field if the field is not found during deserialization.

Changed in version 2.0.0: default value is only used if explicitly set. Otherwise, missing values inputs are excluded from serialized output.

Changed in version 3.0.0b8: Add data_key parameter for the specifying the key in the input and output data. This parameter replaced both load_from and dump_to.

Methods:

_bind_to_schema(field_name, schema)

Update field with values from its parent schema.

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

_validate(value)

Perform validation on value.

_validate_missing(value)

Validate missing values.

deserialize(value[, attr, data])

Deserialize value.

fail(key, **kwargs)

Helper method that raises a ValidationError with an error message from self.error_messages.

get_value(obj, attr[, accessor, default])

Return the value for a given key from an object.

make_error(key, **kwargs)

Helper method to make a ValidationError with an error message from self.error_messages.

serialize(attr, obj[, accessor])

Pulls the value for the given key from the object, applies the field's formatting and returns the result.

Attributes:

context

The context dictionary for the parent Schema.

default_error_messages

Default error messages for various kinds of errors.

_bind_to_schema(field_name, schema)[source]

Update field with values from its parent schema. Called by Schema._bind_field.

Parameters:
  • field_name (str) – Field name set in schema.

  • schema (Schema|Field) – Parent object.

_deserialize(value: Any, attr: str | None, data: Mapping[str, Any] | None, **kwargs)[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_serialize(value: Any, attr: str | None, obj: Any, **kwargs)[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

_validate(value)[source]

Perform validation on value. Raise a ValidationError if validation does not succeed.

_validate_missing(value)[source]

Validate missing values. Raise a ValidationError if value should be considered missing.

property context

The context dictionary for the parent Schema.

default_error_messages = {'null': 'Field may not be null.', 'required': 'Missing data for required field.', 'validator_failed': 'Invalid value.'}

Default error messages for various kinds of errors. The keys in this dictionary are passed to Field.make_error. The values are error messages passed to marshmallow.exceptions.ValidationError.

deserialize(value: Any, attr: str | None = None, data: Mapping[str, Any] | None = None, **kwargs)[source]

Deserialize value.

Parameters:
  • value – The value to deserialize.

  • attr – The attribute/key in data to deserialize.

  • data – The raw input data passed to Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – If an invalid value is passed or if a required value is missing.

fail(key: str, **kwargs)[source]

Helper method that raises a ValidationError with an error message from self.error_messages.

Deprecated since version 3.0.0: Use make_error instead.

get_value(obj, attr, accessor=None, default=<marshmallow.missing>)[source]

Return the value for a given key from an object.

Parameters:
  • obj (object) – The object to get the value from.

  • attr (str) – The attribute/key in obj to get the value from.

  • accessor (callable) – A callable used to retrieve the value of attr from the object obj. Defaults to marshmallow.utils.get_value.

make_error(key: str, **kwargs) ValidationError[source]

Helper method to make a ValidationError with an error message from self.error_messages.

serialize(attr: str, obj: Any, accessor: Callable[[Any, str, Any], Any] | None = None, **kwargs)[source]

Pulls the value for the given key from the object, applies the field’s formatting and returns the result.

Parameters:
  • attr – The attribute/key to get from the object.

  • obj – The object to access the attribute/key from.

  • accessor – Function used to access values from obj.

  • kwargs – Field-specific keyword arguments.

class marshmallow.fields.Float(*, allow_nan: bool = False, as_string: bool = False, **kwargs)[source]

A double as an IEEE-754 double precision string.

Parameters:
  • allow_nan (bool) – If True, NaN, Infinity and -Infinity are allowed, even though they are illegal according to the JSON specification.

  • as_string (bool) – If True, format the value as a string.

  • kwargs – The same keyword arguments that Number receives.

Methods:

_validated(value)

Format the value or raise a ValidationError if an error occurs.

Attributes:

default_error_messages

Default error messages.

Classes:

num_type

alias of float

_validated(value)[source]

Format the value or raise a ValidationError if an error occurs.

default_error_messages = {'special': 'Special numeric values (nan or infinity) are not permitted.'}

Default error messages.

num_type

alias of float Methods:

as_integer_ratio()

Return integer ratio.

conjugate()

Return self, the complex conjugate of any float.

fromhex()

Create a floating-point number from a hexadecimal string.

hex()

Return a hexadecimal representation of a floating-point number.

is_integer()

Return True if the float is an integer.

Attributes:

imag

the imaginary part of a complex number

real

the real part of a complex number

class marshmallow.fields.Function(serialize: None | Callable[[Any], Any] | Callable[[Any, dict], Any] = None, deserialize: None | Callable[[Any], Any] | Callable[[Any, dict], Any] = None, **kwargs)[source]

A field that takes the value returned by a function.

Parameters:
  • serialize – A callable from which to retrieve the value. The function must take a single argument obj which is the object to be serialized. It can also optionally take a context argument, which is a dictionary of context variables passed to the serializer. If no callable is provided then the `load_only` flag will be set to True.

  • deserialize – A callable from which to retrieve the value. The function must take a single argument value which is the value to be deserialized. It can also optionally take a context argument, which is a dictionary of context variables passed to the deserializer. If no callable is provided then `value` will be passed through unchanged.

Changed in version 2.3.0: Deprecated func parameter in favor of serialize.

Changed in version 3.0.0a1: Removed func parameter.

Methods:

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

_deserialize(value, attr, data, **kwargs)[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_serialize(value, attr, obj, **kwargs)[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

class marshmallow.fields.IP(*args, exploded=False, **kwargs)[source]

A IP address field.

Parameters:

exploded (bool) – If True, serialize ipv6 address in long form, ie. with groups consisting entirely of zeros included.

New in version 3.8.0.

Methods:

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

Attributes:

default_error_messages

Default error messages for various kinds of errors.

_deserialize(value, attr, data, **kwargs) IPv4Address | IPv6Address | None[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_serialize(value, attr, obj, **kwargs) str | None[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

default_error_messages = {'invalid_ip': 'Not a valid IP address.'}

Default error messages for various kinds of errors. The keys in this dictionary are passed to Field.make_error. The values are error messages passed to marshmallow.exceptions.ValidationError.

class marshmallow.fields.IPInterface(*args, exploded: bool = False, **kwargs)[source]

A IPInterface field.

IP interface is the non-strict form of the IPNetwork type where arbitrary host addresses are always accepted.

IPAddress and mask e.g. ‘192.168.0.2/24’ or ‘192.168.0.2/255.255.255.0’

see https://python.readthedocs.io/en/latest/library/ipaddress.html#interface-objects

Parameters:

exploded (bool) – If True, serialize ipv6 interface in long form, ie. with groups consisting entirely of zeros included.

Methods:

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

Attributes:

default_error_messages

Default error messages for various kinds of errors.

_deserialize(value, attr, data, **kwargs) None | IPv4Interface | IPv6Interface[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_serialize(value, attr, obj, **kwargs) str | None[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

default_error_messages = {'invalid_ip_interface': 'Not a valid IP interface.'}

Default error messages for various kinds of errors. The keys in this dictionary are passed to Field.make_error. The values are error messages passed to marshmallow.exceptions.ValidationError.

class marshmallow.fields.IPv4(*args, exploded=False, **kwargs)[source]

A IPv4 address field.

New in version 3.8.0.

Classes:

DESERIALIZATION_CLASS

alias of IPv4Address

Attributes:

default_error_messages

Default error messages for various kinds of errors.

DESERIALIZATION_CLASS

alias of IPv4Address Attributes:

is_link_local

Test if the address is reserved for link-local.

is_loopback

Test if the address is a loopback address.

is_multicast

Test if the address is reserved for multicast use.

is_private

Test if this address is allocated for private networks.

is_reserved

Test if the address is otherwise IETF reserved.

is_unspecified

Test if the address is unspecified.

packed

The binary representation of this address.

default_error_messages = {'invalid_ip': 'Not a valid IPv4 address.'}

Default error messages for various kinds of errors. The keys in this dictionary are passed to Field.make_error. The values are error messages passed to marshmallow.exceptions.ValidationError.

class marshmallow.fields.IPv4Interface(*args, exploded: bool = False, **kwargs)[source]

A IPv4 Network Interface field.

Classes:

DESERIALIZATION_CLASS

alias of IPv4Interface

Attributes:

default_error_messages

Default error messages for various kinds of errors.

DESERIALIZATION_CLASS

alias of IPv4Interface

default_error_messages = {'invalid_ip_interface': 'Not a valid IPv4 interface.'}

Default error messages for various kinds of errors. The keys in this dictionary are passed to Field.make_error. The values are error messages passed to marshmallow.exceptions.ValidationError.

class marshmallow.fields.IPv6(*args, exploded=False, **kwargs)[source]

A IPv6 address field.

New in version 3.8.0.

Classes:

DESERIALIZATION_CLASS

alias of IPv6Address

Attributes:

default_error_messages

Default error messages for various kinds of errors.

DESERIALIZATION_CLASS

alias of IPv6Address Attributes:

ipv4_mapped

Return the IPv4 mapped address.

is_global

Test if this address is allocated for public networks.

is_link_local

Test if the address is reserved for link-local.

is_loopback

Test if the address is a loopback address.

is_multicast

Test if the address is reserved for multicast use.

is_private

Test if this address is allocated for private networks.

is_reserved

Test if the address is otherwise IETF reserved.

is_site_local

Test if the address is reserved for site-local.

is_unspecified

Test if the address is unspecified.

packed

The binary representation of this address.

scope_id

Identifier of a particular zone of the address's scope.

sixtofour

Return the IPv4 6to4 embedded address.

teredo

Tuple of embedded teredo IPs.

default_error_messages = {'invalid_ip': 'Not a valid IPv6 address.'}

Default error messages for various kinds of errors. The keys in this dictionary are passed to Field.make_error. The values are error messages passed to marshmallow.exceptions.ValidationError.

class marshmallow.fields.IPv6Interface(*args, exploded: bool = False, **kwargs)[source]

A IPv6 Network Interface field.

Classes:

DESERIALIZATION_CLASS

alias of IPv6Interface

Attributes:

default_error_messages

Default error messages for various kinds of errors.

DESERIALIZATION_CLASS

alias of IPv6Interface Attributes:

is_loopback

Test if the address is a loopback address.

is_unspecified

Test if the address is unspecified.

default_error_messages = {'invalid_ip_interface': 'Not a valid IPv6 interface.'}

Default error messages for various kinds of errors. The keys in this dictionary are passed to Field.make_error. The values are error messages passed to marshmallow.exceptions.ValidationError.

marshmallow.fields.Int

alias of Integer Methods:

_validated(value)

Format the value or raise a ValidationError if an error occurs.

Attributes:

default_error_messages

Default error messages.

Classes:

num_type

alias of int

class marshmallow.fields.Integer(*, strict: bool = False, **kwargs)[source]

An integer field.

Parameters:
  • strict – If True, only integer types are valid. Otherwise, any value castable to int is valid.

  • kwargs – The same keyword arguments that Number receives.

Methods:

_validated(value)

Format the value or raise a ValidationError if an error occurs.

Attributes:

default_error_messages

Default error messages.

Classes:

num_type

alias of int

_validated(value)[source]

Format the value or raise a ValidationError if an error occurs.

default_error_messages = {'invalid': 'Not a valid integer.'}

Default error messages.

num_type

alias of int Methods:

as_integer_ratio()

Return integer ratio.

bit_count()

Number of ones in the binary representation of the absolute value of self.

bit_length()

Number of bits necessary to represent self in binary.

conjugate

Returns self, the complex conjugate of any int.

from_bytes([byteorder, signed])

Return the integer represented by the given array of bytes.

to_bytes([length, byteorder, signed])

Return an array of bytes representing an integer.

Attributes:

denominator

the denominator of a rational number in lowest terms

imag

the imaginary part of a complex number

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

class marshmallow.fields.List(cls_or_instance: Field | type, **kwargs)[source]

A list field, composed with another Field class or instance.

Example:

numbers = fields.List(fields.Float())
Parameters:
  • cls_or_instance – A field class or instance.

  • kwargs – The same keyword arguments that Field receives.

Changed in version 2.0.0: The allow_none parameter now applies to deserialization and has the same semantics as the other fields.

Changed in version 3.0.0rc9: Does not serialize scalar values to single-item lists.

Methods:

_bind_to_schema(field_name, schema)

Update field with values from its parent schema.

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

Attributes:

default_error_messages

Default error messages.

_bind_to_schema(field_name, schema)[source]

Update field with values from its parent schema. Called by Schema._bind_field.

Parameters:
  • field_name (str) – Field name set in schema.

  • schema (Schema|Field) – Parent object.

_deserialize(value, attr, data, **kwargs) list[Any][source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_serialize(value, attr, obj, **kwargs) list[Any] | None[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

default_error_messages = {'invalid': 'Not a valid list.'}

Default error messages.

class marshmallow.fields.Mapping(keys: Field | type | None = None, values: Field | type | None = None, **kwargs)[source]

An abstract class for objects with key-value pairs.

Parameters:
  • keys – A field class or instance for dict keys.

  • values – A field class or instance for dict values.

  • kwargs – The same keyword arguments that Field receives.

Note

When the structure of nested data is not known, you may omit the keys and values arguments to prevent content validation.

New in version 3.0.0rc4.

Methods:

_bind_to_schema(field_name, schema)

Update field with values from its parent schema.

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

Attributes:

default_error_messages

Default error messages.

Classes:

mapping_type

alias of dict

_bind_to_schema(field_name, schema)[source]

Update field with values from its parent schema. Called by Schema._bind_field.

Parameters:
  • field_name (str) – Field name set in schema.

  • schema (Schema|Field) – Parent object.

_deserialize(value, attr, data, **kwargs)[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_serialize(value, attr, obj, **kwargs)[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

default_error_messages = {'invalid': 'Not a valid mapping type.'}

Default error messages.

mapping_type

alias of dict Methods:

clear()

copy()

fromkeys([value])

Create a new dictionary with keys from iterable and values set to value.

get(key[, default])

Return the value for key if key is in the dictionary, else default.

items()

keys()

pop(k[,d])

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem()

Remove and return a (key, value) pair as a 2-tuple.

setdefault(key[, default])

Insert key with a value of default if key is not in the dictionary.

update([E, ]**F)

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values()

class marshmallow.fields.Method(serialize: str | None = None, deserialize: str | None = None, **kwargs)[source]

A field that takes the value returned by a Schema method.

Parameters:
  • serialize (str) – The name of the Schema method from which to retrieve the value. The method must take an argument obj (in addition to self) that is the object to be serialized.

  • deserialize (str) – Optional name of the Schema method for deserializing a value The method must take a single argument value, which is the value to deserialize.

Changed in version 2.0.0: Removed optional context parameter on methods. Use self.context instead.

Changed in version 2.3.0: Deprecated method_name parameter in favor of serialize and allow serialize to not be passed at all.

Changed in version 3.0.0: Removed method_name parameter.

Methods:

_bind_to_schema(field_name, schema)

Update field with values from its parent schema.

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

_bind_to_schema(field_name, schema)[source]

Update field with values from its parent schema. Called by Schema._bind_field.

Parameters:
  • field_name (str) – Field name set in schema.

  • schema (Schema|Field) – Parent object.

_deserialize(value, attr, data, **kwargs)[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_serialize(value, attr, obj, **kwargs)[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

class marshmallow.fields.NaiveDateTime(format: str | None = None, *, timezone: timezone | None = None, **kwargs)[source]

A formatted naive datetime string.

Parameters:
  • format – See DateTime.

  • timezone – Used on deserialization. If None, aware datetimes are rejected. If not None, aware datetimes are converted to this timezone before their timezone information is removed.

  • kwargs – The same keyword arguments that Field receives.

New in version 3.0.0rc9.

Methods:

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_deserialize(value, attr, data, **kwargs) datetime[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

class marshmallow.fields.Nested(nested: ~marshmallow.base.SchemaABC | type | str | dict[str, ~marshmallow.fields.Field | type] | ~typing.Callable[[], ~marshmallow.base.SchemaABC | type | dict[str, ~marshmallow.fields.Field | type]], *, dump_default: ~typing.Any = <marshmallow.missing>, default: ~typing.Any = <marshmallow.missing>, only: ~typing.Sequence[str] | ~typing.AbstractSet[str] | None = None, exclude: ~typing.Sequence[str] | ~typing.AbstractSet[str] = (), many: bool = False, unknown: str | None = None, **kwargs)[source]

Allows you to nest a Schema inside a field.

Examples:

class ChildSchema(Schema):
    id = fields.Str()
    name = fields.Str()
    # Use lambda functions when you need two-way nesting or self-nesting
    parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True)
    siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name"))))

class ParentSchema(Schema):
    id = fields.Str()
    children = fields.List(
        fields.Nested(ChildSchema(only=("id", "parent", "siblings")))
    )
    spouse = fields.Nested(lambda: ParentSchema(only=("id",)))

When passing a Schema instance as the first argument, the instance’s exclude, only, and many attributes will be respected.

Therefore, when passing the exclude, only, or many arguments to fields.Nested, you should pass a Schema class (not an instance) as the first argument.

# Yes
author = fields.Nested(UserSchema, only=('id', 'name'))

# No
author = fields.Nested(UserSchema(), only=('id', 'name'))
Parameters:
  • nestedSchema instance, class, class name (string), dictionary, or callable that returns a Schema or dictionary. Dictionaries are converted with Schema.from_dict.

  • exclude – A list or tuple of fields to exclude.

  • only – A list or tuple of fields to marshal. If None, all fields are marshalled. This parameter takes precedence over exclude.

  • many – Whether the field is a collection of objects.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE.

  • kwargs – The same keyword arguments that Field receives.

Methods:

_deserialize(value, attr, data[, partial])

Same as Field._deserialize() with additional partial argument.

_serialize(nested_obj, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

Attributes:

default_error_messages

Default error messages.

schema

The nested Schema object.

_deserialize(value, attr, data, partial=None, **kwargs)[source]

Same as Field._deserialize() with additional partial argument.

Parameters:

partial (bool|tuple) – For nested schemas, the partial parameter passed to Schema.load.

Changed in version 3.0.0: Add partial parameter.

_serialize(nested_obj, attr, obj, **kwargs)[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

default_error_messages = {'type': 'Invalid type.'}

Default error messages.

property schema

The nested Schema object.

Changed in version 1.0.0: Renamed from serializer to schema.

class marshmallow.fields.Number(*, as_string: bool = False, **kwargs)[source]

Base class for number fields.

Parameters:
  • as_string (bool) – If True, format the serialized value as a string.

  • kwargs – The same keyword arguments that Field receives.

Methods:

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_format_num(value)

Return the number value for value, given this field's num_type.

_serialize(value, attr, obj, **kwargs)

Return a string if self.as_string=True, otherwise return this field's num_type.

_validated(value)

Format the value or raise a ValidationError if an error occurs.

Attributes:

default_error_messages

Default error messages.

Classes:

num_type

alias of float

_deserialize(value, attr, data, **kwargs) _T | None[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_format_num(value) Any[source]

Return the number value for value, given this field’s num_type.

_serialize(value, attr, obj, **kwargs) str | _T | None[source]

Return a string if self.as_string=True, otherwise return this field’s num_type.

_validated(value) _T | None[source]

Format the value or raise a ValidationError if an error occurs.

default_error_messages = {'invalid': 'Not a valid number.', 'too_large': 'Number too large.'}

Default error messages.

num_type

alias of float Methods:

as_integer_ratio()

Return integer ratio.

conjugate()

Return self, the complex conjugate of any float.

fromhex()

Create a floating-point number from a hexadecimal string.

hex()

Return a hexadecimal representation of a floating-point number.

is_integer()

Return True if the float is an integer.

Attributes:

imag

the imaginary part of a complex number

real

the real part of a complex number

class marshmallow.fields.Pluck(nested: SchemaABC | type | str | Callable[[], SchemaABC], field_name: str, **kwargs)[source]

Allows you to replace nested data with one of the data’s fields.

Example:

from marshmallow import Schema, fields

class ArtistSchema(Schema):
    id = fields.Int()
    name = fields.Str()

class AlbumSchema(Schema):
    artist = fields.Pluck(ArtistSchema, 'id')


in_data = {'artist': 42}
loaded = AlbumSchema().load(in_data) # => {'artist': {'id': 42}}
dumped = AlbumSchema().dump(loaded)  # => {'artist': 42}
Parameters:
  • nested (Schema) – The Schema class or class name (string) to nest, or "self" to nest the Schema within itself.

  • field_name (str) – The key to pluck a value from.

  • kwargs – The same keyword arguments that Nested receives.

Methods:

_deserialize(value, attr, data[, partial])

Same as Field._deserialize() with additional partial argument.

_serialize(nested_obj, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

_deserialize(value, attr, data, partial=None, **kwargs)[source]

Same as Field._deserialize() with additional partial argument.

Parameters:

partial (bool|tuple) – For nested schemas, the partial parameter passed to Schema.load.

Changed in version 3.0.0: Add partial parameter.

_serialize(nested_obj, attr, obj, **kwargs)[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

class marshmallow.fields.Raw(*, load_default: ~typing.Any = <marshmallow.missing>, missing: ~typing.Any = <marshmallow.missing>, dump_default: ~typing.Any = <marshmallow.missing>, default: ~typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: None | ~typing.Callable[[~typing.Any], ~typing.Any] | ~typing.Iterable[~typing.Callable[[~typing.Any], ~typing.Any]] = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str] | None = None, metadata: ~typing.Mapping[str, ~typing.Any] | None = None, **additional_metadata)[source]

Field that applies no formatting.

marshmallow.fields.Str

alias of String Methods:

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

Attributes:

default_error_messages

Default error messages.

class marshmallow.fields.String(*, load_default: ~typing.Any = <marshmallow.missing>, missing: ~typing.Any = <marshmallow.missing>, dump_default: ~typing.Any = <marshmallow.missing>, default: ~typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: None | ~typing.Callable[[~typing.Any], ~typing.Any] | ~typing.Iterable[~typing.Callable[[~typing.Any], ~typing.Any]] = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str] | None = None, metadata: ~typing.Mapping[str, ~typing.Any] | None = None, **additional_metadata)[source]

A string field.

Parameters:

kwargs – The same keyword arguments that Field receives.

Methods:

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

Attributes:

default_error_messages

Default error messages.

_deserialize(value, attr, data, **kwargs) Any[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_serialize(value, attr, obj, **kwargs) str | None[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

default_error_messages = {'invalid': 'Not a valid string.', 'invalid_utf8': 'Not a valid utf-8 string.'}

Default error messages.

class marshmallow.fields.Time(format: str | None = None, **kwargs)[source]

A formatted time string.

Example: '03:12:58.019077'

Parameters:
  • format – Either "iso" (for ISO8601) or a date format string. If None, defaults to “iso”.

  • kwargs – The same keyword arguments that Field receives.

class marshmallow.fields.TimeDelta(precision: str = 'seconds', serialization_type: type[int | float] = <class 'int'>, **kwargs)[source]

A field that (de)serializes a datetime.timedelta object to an integer or float and vice versa. The integer or float can represent the number of days, seconds or microseconds.

Parameters:
  • precision – Influences how the integer or float is interpreted during (de)serialization. Must be ‘days’, ‘seconds’, ‘microseconds’, ‘milliseconds’, ‘minutes’, ‘hours’ or ‘weeks’.

  • serialization_type – Whether to (de)serialize to a int or float.

  • kwargs – The same keyword arguments that Field receives.

Integer Caveats

Any fractional parts (which depends on the precision used) will be truncated when serializing using int.

Float Caveats

Use of float when (de)serializing may result in data precision loss due to the way machines handle floating point values.

Regardless of the precision chosen, the fractional part when using float will always be truncated to microseconds. For example, 1.12345 interpreted as microseconds will result in timedelta(microseconds=1).

Changed in version 2.0.0: Always serializes to an integer value to avoid rounding errors. Add precision parameter.

Changed in version 3.17.0: Allow (de)serialization to float through use of a new serialization_type parameter. int is the default to retain previous behaviour.

Methods:

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

Attributes:

default_error_messages

Default error messages.

_deserialize(value, attr, data, **kwargs)[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_serialize(value, attr, obj, **kwargs)[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

default_error_messages = {'format': '{input!r} cannot be formatted as a timedelta.', 'invalid': 'Not a valid period of time.'}

Default error messages.

class marshmallow.fields.Tuple(tuple_fields, *args, **kwargs)[source]

A tuple field, composed of a fixed number of other Field classes or instances

Example:

row = Tuple((fields.String(), fields.Integer(), fields.Float()))

Note

Because of the structured nature of collections.namedtuple and typing.NamedTuple, using a Schema within a Nested field for them is more appropriate than using a Tuple field.

Parameters:
  • tuple_fields (Iterable[Field]) – An iterable of field classes or instances.

  • kwargs – The same keyword arguments that Field receives.

New in version 3.0.0rc4.

Methods:

_bind_to_schema(field_name, schema)

Update field with values from its parent schema.

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_serialize(value, attr, obj, **kwargs)

Serializes value to a basic Python datatype.

Attributes:

default_error_messages

Default error messages.

_bind_to_schema(field_name, schema)[source]

Update field with values from its parent schema. Called by Schema._bind_field.

Parameters:
  • field_name (str) – Field name set in schema.

  • schema (Schema|Field) – Parent object.

_deserialize(value, attr, data, **kwargs) tuple[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_serialize(value, attr, obj, **kwargs) tuple | None[source]

Serializes value to a basic Python datatype. Noop by default. Concrete Field classes should implement this method.

Example:

class TitleCase(Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if not value:
            return ''
        return str(value).title()
Parameters:
  • value – The value to be serialized.

  • attr (str) – The attribute or key on the object to be serialized.

  • obj (object) – The object the value was pulled from.

  • kwargs (dict) – Field-specific keyword arguments.

Returns:

The serialized value

default_error_messages = {'invalid': 'Not a valid tuple.'}

Default error messages.

marshmallow.fields.URL

alias of Url Attributes:

default_error_messages

Default error messages.

class marshmallow.fields.UUID(*, load_default: ~typing.Any = <marshmallow.missing>, missing: ~typing.Any = <marshmallow.missing>, dump_default: ~typing.Any = <marshmallow.missing>, default: ~typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: None | ~typing.Callable[[~typing.Any], ~typing.Any] | ~typing.Iterable[~typing.Callable[[~typing.Any], ~typing.Any]] = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str] | None = None, metadata: ~typing.Mapping[str, ~typing.Any] | None = None, **additional_metadata)[source]

A UUID field.

Methods:

_deserialize(value, attr, data, **kwargs)

Deserialize value.

_validated(value)

Format the value or raise a ValidationError if an error occurs.

Attributes:

default_error_messages

Default error messages.

_deserialize(value, attr, data, **kwargs) UUID | None[source]

Deserialize value. Concrete Field classes should implement this method.

Parameters:
  • value – The value to be deserialized.

  • attr – The attribute/key in data to be deserialized.

  • data – The raw input data passed to the Schema.load.

  • kwargs – Field-specific keyword arguments.

Raises:

ValidationError – In case of formatting or validation failure.

Returns:

The deserialized value.

Changed in version 2.0.0: Added attr and data parameters.

Changed in version 3.0.0: Added **kwargs to signature.

_validated(value) UUID | None[source]

Format the value or raise a ValidationError if an error occurs.

default_error_messages = {'invalid_uuid': 'Not a valid UUID.'}

Default error messages.

class marshmallow.fields.Url(*, relative: bool = False, absolute: bool = True, schemes: Sequence[str] | AbstractSet[str] | None = None, require_tld: bool = True, **kwargs)[source]

An URL field.

Parameters:
  • default – Default value for the field if the attribute is not set.

  • relative – Whether to allow relative URLs.

  • require_tld – Whether to reject non-FQDN hostnames.

  • schemes – Valid schemes. By default, http, https, ftp, and ftps are allowed.

  • kwargs – The same keyword arguments that String receives.

Attributes:

default_error_messages

Default error messages.

default_error_messages = {'invalid': 'Not a valid URL.'}

Default error messages.