nitpick.fields module

Custom Marshmallow fields and validators.

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

Bases: marshmallow.fields.Mapping

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.

property context

The context dictionary for the parent Schema.

default_error_messages = {'invalid': 'Not a valid mapping type.'}
deserialize(value: Any, attr: str = None, data: Mapping[str, Any] = None, **kwargs)

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)

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

Deprecated since version 3.0.0: Use make_error <marshmallow.fields.Field.make_error> instead.

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

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)marshmallow.exceptions.ValidationError

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

mapping_type

alias of builtins.dict

name = None
parent = None
property root

Reference to the Schema that this field belongs to even if it is buried in a container field (e.g. List). Return None for unbound fields.

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

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 nitpick.fields.Field(*, default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, data_key: str = None, attribute: str = None, validate: Union[Callable[[Any], Any], Iterable[Callable[[Any], Any]]] = None, required: bool = False, allow_none: bool = None, load_only: bool = False, dump_only: bool = False, error_messages: Dict[str, str] = None, **metadata)[source]

Bases: marshmallow.base.FieldABC

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
  • 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.

  • missing – 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 attribute to get the value from when serializing. If None, assumes the attribute has the same name as the field. Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute. 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 missing=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 arguments to be stored as 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.

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, data: Mapping[str, Any] = 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 <marshmallow.fields.Field.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)marshmallow.exceptions.ValidationError[source]

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

name = None
parent = None
property root

Reference to the Schema that this field belongs to even if it is buried in a container field (e.g. List). Return None for unbound fields.

serialize(attr: str, obj: Any, accessor: Callable[[Any, str, Any], Any] = 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 nitpick.fields.List(cls_or_instance: Union[marshmallow.fields.Field, type], **kwargs)[source]

Bases: marshmallow.fields.Field

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.

property context

The context dictionary for the parent Schema.

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

Default error messages.

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

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)

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

Deprecated since version 3.0.0: Use make_error <marshmallow.fields.Field.make_error> instead.

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

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)marshmallow.exceptions.ValidationError

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

name = None
parent = None
property root

Reference to the Schema that this field belongs to even if it is buried in a container field (e.g. List). Return None for unbound fields.

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

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 nitpick.fields.Nested(nested: Union[marshmallow.base.SchemaABC, type, str, Callable[[], marshmallow.base.SchemaABC]], *, default: Any = <marshmallow.missing>, only: Union[Sequence[str], Set[str]] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, unknown: str = None, **kwargs)[source]

Bases: marshmallow.fields.Field

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 <marshmallow.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 <marshmallow.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), or callable that returns a Schema instance.

  • 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.

property context

The context dictionary for the parent Schema.

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

Default error messages.

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

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)

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

Deprecated since version 3.0.0: Use make_error <marshmallow.fields.Field.make_error> instead.

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

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)marshmallow.exceptions.ValidationError

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

name = None
parent = None
property root

Reference to the Schema that this field belongs to even if it is buried in a container field (e.g. List). Return None for unbound fields.

property schema

The nested Schema object.

Changed in version 1.0.0: Renamed from serializer to schema.

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

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 nitpick.fields.String(*, default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, data_key: str = None, attribute: str = None, validate: Union[Callable[[Any], Any], Iterable[Callable[[Any], Any]]] = None, required: bool = False, allow_none: bool = None, load_only: bool = False, dump_only: bool = False, error_messages: Dict[str, str] = None, **metadata)[source]

Bases: marshmallow.fields.Field

A string field.

Parameters

kwargs – The same keyword arguments that Field receives.

property context

The context dictionary for the parent Schema.

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

Default error messages.

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

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)

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

Deprecated since version 3.0.0: Use make_error <marshmallow.fields.Field.make_error> instead.

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

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)marshmallow.exceptions.ValidationError

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

name = None
parent = None
property root

Reference to the Schema that this field belongs to even if it is buried in a container field (e.g. List). Return None for unbound fields.

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

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.