nitpick.fields module
Custom Marshmallow fields and validators.
- class nitpick.fields.Dict(keys: Field | type | None = None, values: Field | type | None = None, **kwargs)[source]
Bases:
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
.
- property default
- default_error_messages = {'invalid': 'Not a valid mapping type.'}
Default error messages.
- deserialize(value: Any, attr: str | None = None, data: Mapping[str, Any] | None = 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.
- make_error(key: str, **kwargs) ValidationError
Helper method to make a ValidationError with an error message from
self.error_messages
.
- property missing
- name = None
- parent = None
- root = None
- serialize(attr: str, obj: Any, accessor: Callable[[Any, str, Any], Any] | None = 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(*, 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]
Bases:
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:
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 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
load_default=None
andallow_none
is unset, will default toTrue
. Otherwise, the default isFalse
.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 bothload_from
anddump_to
.- property context
The context dictionary for the parent
Schema
.
- property default
- 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 <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.
- make_error(key: str, **kwargs) ValidationError [source]
Helper method to make a ValidationError with an error message from
self.error_messages
.
- property missing
- name = None
- parent = None
- root = None
- 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 nitpick.fields.List(cls_or_instance: Field | type, **kwargs)[source]
Bases:
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
.
- property default
- default_error_messages = {'invalid': 'Not a valid list.'}
Default error messages.
- deserialize(value: Any, attr: str | None = None, data: Mapping[str, Any] | None = 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.
- make_error(key: str, **kwargs) ValidationError
Helper method to make a ValidationError with an error message from
self.error_messages
.
- property missing
- name = None
- parent = None
- root = None
- serialize(attr: str, obj: Any, accessor: Callable[[Any, str, Any], Any] | None = 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: SchemaABC | type | str | dict[str, Field | type] | typing.Callable[[], SchemaABC | dict[str, Field | type]], *, dump_default: typing.Any = <marshmallow.missing>, default: typing.Any = <marshmallow.missing>, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, unknown: str | None = None, **kwargs)[source]
Bases:
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
, andmany
attributes will be respected.Therefore, when passing the
exclude
,only
, ormany
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:
nested – Schema 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.
- property context
The context dictionary for the parent
Schema
.
- property default
- default_error_messages = {'type': 'Invalid type.'}
Default error messages.
- deserialize(value: Any, attr: str | None = None, data: Mapping[str, Any] | None = 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.
- make_error(key: str, **kwargs) ValidationError
Helper method to make a ValidationError with an error message from
self.error_messages
.
- property missing
- name = None
- parent = None
- root = None
- 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 = 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(*, 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]
Bases:
Field
A string field.
- Parameters:
kwargs – The same keyword arguments that
Field
receives.
- property context
The context dictionary for the parent
Schema
.
- property default
- 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 = None, data: Mapping[str, Any] | None = 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.
- make_error(key: str, **kwargs) ValidationError
Helper method to make a ValidationError with an error message from
self.error_messages
.
- property missing
- name = None
- parent = None
- root = None
- serialize(attr: str, obj: Any, accessor: Callable[[Any, str, Any], Any] | None = 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.