prompt: 3.0: DateTime fields cannot be used as inner field for List or Tuple fields
  Between releases 3.0.0rc8 and 3.0.0rc9, `DateTime` fields have started throwing an error when being instantiated as inner fields of container fields like `List` or `Tuple`. The snippet below works in <=3.0.0rc8 and throws the error below in >=3.0.0rc9 (and, worryingly, 3.0.0):
  
  ```python
  from marshmallow import fields, Schema
  
  class MySchema(Schema):
      times = fields.List(fields.DateTime())
  
  s = MySchema()
  ```
  
  Traceback:
  ```
  Traceback (most recent call last):
    File "test-mm.py", line 8, in <module>
      s = MySchema()
    File "/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/schema.py", line 383, in __init__
      self.fields = self._init_fields()
    File "/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/schema.py", line 913, in _init_fields
      self._bind_field(field_name, field_obj)
    File "/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/schema.py", line 969, in _bind_field
      field_obj._bind_to_schema(field_name, self)
    File "/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/fields.py", line 636, in _bind_to_schema
      self.inner._bind_to_schema(field_name, self)
    File "/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/fields.py", line 1117, in _bind_to_schema
      or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME)
  AttributeError: 'List' object has no attribute 'opts'
  ```
  
  It seems like it's treating the parent field as a Schema without checking that it is indeed a schema, so the `schema.opts` statement fails as fields don't have an `opts` attribute.
  
instance: {"FAIL_TO_PASS": "[\"tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format\"]", "PASS_TO_PASS": "[\"tests/test_fields.py::test_field_aliases[Integer-Integer]\", \"tests/test_fields.py::test_field_aliases[String-String]\", \"tests/test_fields.py::test_field_aliases[Boolean-Boolean]\", \"tests/test_fields.py::test_field_aliases[Url-Url]\", \"tests/test_fields.py::TestField::test_repr\", \"tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed\", \"tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field\", \"tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj\", \"tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set\", \"tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set\", \"tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name\", \"tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none\", \"tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name\", \"tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name\", \"tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name\", \"tests/test_fields.py::TestParentAndName::test_simple_field_root\", \"tests/test_fields.py::TestParentAndName::test_list_field_inner_root\", \"tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root\", \"tests/test_fields.py::TestParentAndName::test_list_root_inheritance\", \"tests/test_fields.py::TestParentAndName::test_dict_root_inheritance\", \"tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]\", \"tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]\", \"tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]\", \"tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]\", \"tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]\", \"tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]\", \"tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]\", \"tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]\", \"tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]\", \"tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]\", \"tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]\", \"tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]\", \"tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]\", \"tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]\", \"tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg\", \"tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages\", \"tests/test_fields.py::TestErrorMessages::test_make_error[required-Missing\", \"tests/test_fields.py::TestErrorMessages::test_make_error[null-Field\", \"tests/test_fields.py::TestErrorMessages::test_make_error[custom-Custom\", \"tests/test_fields.py::TestErrorMessages::test_make_error[validator_failed-Invalid\", \"tests/test_fields.py::TestErrorMessages::test_fail[required-Missing\", \"tests/test_fields.py::TestErrorMessages::test_fail[null-Field\", \"tests/test_fields.py::TestErrorMessages::test_fail[custom-Custom\", \"tests/test_fields.py::TestErrorMessages::test_fail[validator_failed-Invalid\", \"tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist\", \"tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]\", \"tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]\", \"tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]\", \"tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]\", \"tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]\", \"tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]\", \"tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]\", \"tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]\", \"tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]\", \"tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]\", \"tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]\", \"tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]\", \"tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]\", \"tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]\", \"tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]\", \"tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]\", \"tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]\", \"tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]\", \"tests/test_fields.py::TestListNested::test_list_nested_only_and_exclude_merged_with_nested[only-expected0]\", \"tests/test_fields.py::TestListNested::test_list_nested_only_and_exclude_merged_with_nested[exclude-expected1]\", \"tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested\", \"tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]\", \"tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]\", \"tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested\", \"tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]\", \"tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]\", \"tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]\", \"tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]\", \"tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]\", \"tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]\", \"tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested\"]", "base_commit": "b40a0f4e33823e6d0f341f7e8684e359a99060d1", "created_at": "2019-08-21T15:45:13Z", "environment_setup_commit": "8b3a32614fd4a74e93e9a63a042e74c1fea34466", "hints_text": "Thanks for reporting. I don't think I'll have time to look into this until the weekend. Would you like to send a PR? \nI'm afraid I don't have any time either, and I don't really have enough context on the `_bind_to_schema` process to make sure I'm not breaking stuff.\nOK, no problem. @lafrech Will you have a chance to look into this?\nI've found the patch below to fix the minimal example above, but I'm not really sure what it's missing out on or how to test it properly:\r\n```patch\r\ndiff --git a/src/marshmallow/fields.py b/src/marshmallow/fields.py\r\nindex 0b18e7d..700732e 100644\r\n--- a/src/marshmallow/fields.py\r\n+++ b/src/marshmallow/fields.py\r\n@@ -1114,7 +1114,7 @@ class DateTime(Field):\r\n         super()._bind_to_schema(field_name, schema)\r\n         self.format = (\r\n             self.format\r\n-            or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME)\r\n+            or getattr(getattr(schema, \"opts\", None), self.SCHEMA_OPTS_VAR_NAME, None)\r\n             or self.DEFAULT_FORMAT\r\n         )\r\n```\n    git difftool 3.0.0rc8 3.0.0rc9 src/marshmallow/fields.py\r\n\r\nWhen reworking container stuff, I changed\r\n\r\n```py\r\n        self.inner.parent = self\r\n        self.inner.name = field_name\r\n```\r\ninto\r\n\r\n```py\r\n        self.inner._bind_to_schema(field_name, self)\r\n```\r\n\r\nAFAIR, I did this merely to avoid duplication. On second thought, I think it was the right thing to do, not only for duplication but to actually bind inner fields to the `Schema`.\r\n\r\nReverting this avoids the error but the inner field's `_bind_to_schema` method is not called so I'm not sure it is desirable.\r\n\r\nI think we really mean to call that method, not only in this case but also generally.\r\n\r\nChanging\r\n\r\n```py\r\n            or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME)\r\n```\r\n\r\ninto\r\n\r\n```py\r\n            or getattr(self.root.opts, self.SCHEMA_OPTS_VAR_NAME)\r\n```\r\n\r\nmight be a better fix. Can anyone confirm (@sloria, @deckar01)?\r\n\r\nThe fix in https://github.com/marshmallow-code/marshmallow/issues/1357#issuecomment-523465528 removes the error but also the feature: `DateTime` fields buried into container fields won't respect the format set in the `Schema`.\r\n\r\nI didn't double-check that but AFAIU, the change I mentioned above (in container stuff rework) was the right thing to do. The feature was already broken (format set in `Schema` not respected if `DateTime` field in container field) and that's just one of the issues that may arise due to the inner field not being bound to the `Schema`. But I may be wrong.\nOn quick glance, your analysis and fix look correct @lafrech \nLet's do that, then.\r\n\r\nNot much time either. The first who gets the time can do it.\r\n\r\nFor the non-reg tests :\r\n\r\n1/ a test that checks the format set in the schema is respected if the `DateTime` field is in a container field\r\n\r\n2/ a set of tests asserting the `_bind_to_schema` method of inner fields `List`, `Dict`, `Tuple` is called from container fields (we can use `DateTime` with the same test case for that)\r\n\r\nPerhaps 1/ is useless if 2/ is done.", "instance_id": "marshmallow-code__marshmallow-1359", "patch": "diff --git a/src/marshmallow/fields.py b/src/marshmallow/fields.py\n--- a/src/marshmallow/fields.py\n+++ b/src/marshmallow/fields.py\n@@ -1114,7 +1114,7 @@ def _bind_to_schema(self, field_name, schema):\n         super()._bind_to_schema(field_name, schema)\n         self.format = (\n             self.format\n-            or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME)\n+            or getattr(self.root.opts, self.SCHEMA_OPTS_VAR_NAME)\n             or self.DEFAULT_FORMAT\n         )\n \n", "problem_statement": "3.0: DateTime fields cannot be used as inner field for List or Tuple fields\nBetween releases 3.0.0rc8 and 3.0.0rc9, `DateTime` fields have started throwing an error when being instantiated as inner fields of container fields like `List` or `Tuple`. The snippet below works in <=3.0.0rc8 and throws the error below in >=3.0.0rc9 (and, worryingly, 3.0.0):\r\n\r\n```python\r\nfrom marshmallow import fields, Schema\r\n\r\nclass MySchema(Schema):\r\n    times = fields.List(fields.DateTime())\r\n\r\ns = MySchema()\r\n```\r\n\r\nTraceback:\r\n```\r\nTraceback (most recent call last):\r\n  File \"test-mm.py\", line 8, in <module>\r\n    s = MySchema()\r\n  File \"/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/schema.py\", line 383, in __init__\r\n    self.fields = self._init_fields()\r\n  File \"/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/schema.py\", line 913, in _init_fields\r\n    self._bind_field(field_name, field_obj)\r\n  File \"/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/schema.py\", line 969, in _bind_field\r\n    field_obj._bind_to_schema(field_name, self)\r\n  File \"/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/fields.py\", line 636, in _bind_to_schema\r\n    self.inner._bind_to_schema(field_name, self)\r\n  File \"/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/fields.py\", line 1117, in _bind_to_schema\r\n    or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME)\r\nAttributeError: 'List' object has no attribute 'opts'\r\n```\r\n\r\nIt seems like it's treating the parent field as a Schema without checking that it is indeed a schema, so the `schema.opts` statement fails as fields don't have an `opts` attribute.\n", "repo": "marshmallow-code/marshmallow", "test_patch": "diff --git a/tests/test_fields.py b/tests/test_fields.py\n--- a/tests/test_fields.py\n+++ b/tests/test_fields.py\n@@ -169,6 +169,20 @@ class OtherSchema(MySchema):\n         assert schema2.fields[\"foo\"].key_field.root == schema2\n         assert schema2.fields[\"foo\"].value_field.root == schema2\n \n+    # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1357\n+    def test_datetime_list_inner_format(self, schema):\n+        class MySchema(Schema):\n+            foo = fields.List(fields.DateTime())\n+            bar = fields.Tuple((fields.DateTime(),))\n+\n+            class Meta:\n+                datetimeformat = \"iso8601\"\n+                dateformat = \"iso8601\"\n+\n+        schema = MySchema()\n+        assert schema.fields[\"foo\"].inner.format == \"iso8601\"\n+        assert schema.fields[\"bar\"].tuple_fields[0].format == \"iso8601\"\n+\n \n class TestMetadata:\n     @pytest.mark.parametrize(\"FieldClass\", ALL_FIELDS)\n", "version": "3.0"}
parsed_commit_content: {"file_diffs":[{"old_file_content":"\"\"\"Field classes for various types of data.\"\"\"\n\nimport collections\nimport copy\nimport datetime as dt\nimport numbers\nimport uuid\nimport decimal\nimport math\nimport warnings\nfrom collections.abc import Mapping as _Mapping\n\nfrom marshmallow import validate, utils, class_registry\nfrom marshmallow.base import FieldABC, SchemaABC\nfrom marshmallow.utils import (\n    is_collection,\n    missing as missing_,\n    resolve_field_instance,\n    is_aware,\n)\nfrom marshmallow.exceptions import (\n    ValidationError,\n    StringNotCollectionError,\n    FieldInstanceResolutionError,\n)\nfrom marshmallow.validate import Validator, Length\n\n__all__ = [\n    \"Field\",\n    \"Raw\",\n    \"Nested\",\n    \"Mapping\",\n    \"Dict\",\n    \"List\",\n    \"Tuple\",\n    \"String\",\n    \"UUID\",\n    \"Number\",\n    \"Integer\",\n    \"Decimal\",\n    \"Boolean\",\n    \"Float\",\n    \"DateTime\",\n    \"NaiveDateTime\",\n    \"AwareDateTime\",\n    \"Time\",\n    \"Date\",\n    \"TimeDelta\",\n    \"Url\",\n    \"URL\",\n    \"Email\",\n    \"Method\",\n    \"Function\",\n    \"Str\",\n    \"Bool\",\n    \"Int\",\n    \"Constant\",\n    \"Pluck\",\n]\n\nMISSING_ERROR_MESSAGE = (\n    \"ValidationError raised by `{class_name}`, but error key `{key}` does \"\n    \"not exist in the `error_messages` dictionary.\"\n)\n\n\nclass Field(FieldABC):\n    \"\"\"Basic field from which other fields should extend. It applies no\n    formatting by default, and should only be used in cases where\n    data does not need to be formatted before being serialized or deserialized.\n    On error, the name of the field will be returned.\n\n    :param default: If set, this value will be used during serialization if the input value\n        is missing. If not set, the field will be excluded from the serialized output if the\n        input value is missing. May be a value or a callable.\n    :param missing: Default deserialization value for the field if the field is not\n        found in the input data. May be a value or a callable.\n    :param str data_key: The name of the dict key in the external representation, i.e.\n        the input of `load` and the output of `dump`.\n        If `None`, the key will match the name of the field.\n    :param str attribute: The name of the attribute to get the value from when serializing.\n        If `None`, assumes the attribute has the same name as the field.\n        Note: This should only be used for very specific use cases such as\n        outputting multiple fields for a single attribute. In most cases,\n        you should use ``data_key`` instead.\n    :param callable validate: Validator or collection of validators that are called\n        during deserialization. Validator takes a field's input value as\n        its only parameter and returns a boolean.\n        If it returns `False`, an :exc:`ValidationError` is raised.\n    :param required: Raise a :exc:`ValidationError` if the field value\n        is not supplied during deserialization.\n    :param allow_none: Set this to `True` if `None` should be considered a valid value during\n        validation/deserialization. If ``missing=None`` and ``allow_none`` is unset,\n        will default to ``True``. Otherwise, the default is ``False``.\n    :param bool load_only: If `True` skip this field during serialization, otherwise\n        its value will be present in the serialized data.\n    :param bool dump_only: If `True` skip this field during deserialization, otherwise\n        its value will be present in the deserialized object. In the context of an\n        HTTP API, this effectively marks the field as \"read-only\".\n    :param dict error_messages: Overrides for `Field.default_error_messages`.\n    :param metadata: Extra arguments to be stored as metadata.\n\n    .. versionchanged:: 2.0.0\n        Removed `error` parameter. Use ``error_messages`` instead.\n\n    .. versionchanged:: 2.0.0\n        Added `allow_none` parameter, which makes validation/deserialization of `None`\n        consistent across fields.\n\n    .. versionchanged:: 2.0.0\n        Added `load_only` and `dump_only` parameters, which allow field skipping\n        during the (de)serialization process.\n\n    .. versionchanged:: 2.0.0\n        Added `missing` parameter, which indicates the value for a field if the field\n        is not found during deserialization.\n\n    .. versionchanged:: 2.0.0\n        ``default`` value is only used if explicitly set. Otherwise, missing values\n        inputs are excluded from serialized output.\n\n    .. versionchanged:: 3.0.0b8\n        Add ``data_key`` parameter for the specifying the key in the input and\n        output data. This parameter replaced both ``load_from`` and ``dump_to``.\n    \"\"\"\n\n    # Some fields, such as Method fields and Function fields, are not expected\n    #  to exist as attributes on the objects to serialize. Set this to False\n    #  for those fields\n    _CHECK_ATTRIBUTE = True\n    _creation_index = 0  # Used for sorting\n\n    #: Default error messages for various kinds of errors. The keys in this dictionary\n    #: are passed to `Field.fail`. The values are error messages passed to\n    #: :exc:`marshmallow.exceptions.ValidationError`.\n    default_error_messages = {\n        \"required\": \"Missing data for required field.\",\n        \"null\": \"Field may not be null.\",\n        \"validator_failed\": \"Invalid value.\",\n    }\n\n    def __init__(\n        self,\n        *,\n        default=missing_,\n        missing=missing_,\n        data_key=None,\n        attribute=None,\n        validate=None,\n        required=False,\n        allow_none=None,\n        load_only=False,\n        dump_only=False,\n        error_messages=None,\n        **metadata\n    ):\n        self.default = default\n        self.attribute = attribute\n        self.data_key = data_key\n        self.validate = validate\n        if utils.is_iterable_but_not_string(validate):\n            if not utils.is_generator(validate):\n                self.validators = validate\n            else:\n                self.validators = list(validate)\n        elif callable(validate):\n            self.validators = [validate]\n        elif validate is None:\n            self.validators = []\n        else:\n            raise ValueError(\n                \"The 'validate' parameter must be a callable \"\n                \"or a collection of callables.\"\n            )\n\n        # If missing=None, None should be considered valid by default\n        if allow_none is None:\n            if missing is None:\n                self.allow_none = True\n            else:\n                self.allow_none = False\n        else:\n            self.allow_none = allow_none\n        self.load_only = load_only\n        self.dump_only = dump_only\n        if required is True and missing is not missing_:\n            raise ValueError(\"'missing' must not be set for required fields.\")\n        self.required = required\n        self.missing = missing\n        self.metadata = metadata\n        self._creation_index = Field._creation_index\n        Field._creation_index += 1\n\n        # Collect default error message from self and parent classes\n        messages = {}\n        for cls in reversed(self.__class__.__mro__):\n            messages.update(getattr(cls, \"default_error_messages\", {}))\n        messages.update(error_messages or {})\n        self.error_messages = messages\n\n    def __repr__(self):\n        return (\n            \"<fields.{ClassName}(default={self.default!r}, \"\n            \"attribute={self.attribute!r}, \"\n            \"validate={self.validate}, required={self.required}, \"\n            \"load_only={self.load_only}, dump_only={self.dump_only}, \"\n            \"missing={self.missing}, allow_none={self.allow_none}, \"\n            \"error_messages={self.error_messages})>\".format(\n                ClassName=self.__class__.__name__, self=self\n            )\n        )\n\n    def __deepcopy__(self, memo):\n        return copy.copy(self)\n\n    def get_value(self, obj, attr, accessor=None, default=missing_):\n        \"\"\"Return the value for a given key from an object.\n\n        :param object obj: The object to get the value from.\n        :param str attr: The attribute/key in `obj` to get the value from.\n        :param callable accessor: A callable used to retrieve the value of `attr` from\n            the object `obj`. Defaults to `marshmallow.utils.get_value`.\n        \"\"\"\n        # NOTE: Use getattr instead of direct attribute access here so that\n        # subclasses aren't required to define `attribute` member\n        attribute = getattr(self, \"attribute\", None)\n        accessor_func = accessor or utils.get_value\n        check_key = attr if attribute is None else attribute\n        return accessor_func(obj, check_key, default)\n\n    def _validate(self, value):\n        \"\"\"Perform validation on ``value``. Raise a :exc:`ValidationError` if validation\n        does not succeed.\n        \"\"\"\n        errors = []\n        kwargs = {}\n        for validator in self.validators:\n            try:\n                r = validator(value)\n                if not isinstance(validator, Validator) and r is False:\n                    raise self.make_error(\"validator_failed\")\n            except ValidationError as err:\n                kwargs.update(err.kwargs)\n                if isinstance(err.messages, dict):\n                    errors.append(err.messages)\n                else:\n                    errors.extend(err.messages)\n        if errors:\n            raise ValidationError(errors, **kwargs)\n\n    def make_error(self, key: str, **kwargs) -> ValidationError:\n        \"\"\"Helper method to make a `ValidationError` with an error message\n        from ``self.error_messages``.\n        \"\"\"\n        try:\n            msg = self.error_messages[key]\n        except KeyError as error:\n            class_name = self.__class__.__name__\n            msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key)\n            raise AssertionError(msg) from error\n        if isinstance(msg, (str, bytes)):\n            msg = msg.format(**kwargs)\n        return ValidationError(msg)\n\n    def fail(self, key: str, **kwargs):\n        \"\"\"Helper method that raises a `ValidationError` with an error message\n        from ``self.error_messages``.\n\n        .. deprecated:: 3.0.0\n            Use `make_error <marshmallow.fields.Field.make_error>` instead.\n        \"\"\"\n        warnings.warn(\n            '`Field.fail` is deprecated. Use `raise self.make_error(\"{}\", ...)` instead.'.format(\n                key\n            ),\n            DeprecationWarning,\n        )\n        raise self.make_error(key=key, **kwargs)\n\n    def _validate_missing(self, value):\n        \"\"\"Validate missing values. Raise a :exc:`ValidationError` if\n        `value` should be considered missing.\n        \"\"\"\n        if value is missing_:\n            if hasattr(self, \"required\") and self.required:\n                raise self.make_error(\"required\")\n        if value is None:\n            if hasattr(self, \"allow_none\") and self.allow_none is not True:\n                raise self.make_error(\"null\")\n\n    def serialize(self, attr, obj, accessor=None, **kwargs):\n        \"\"\"Pulls the value for the given key from the object, applies the\n        field's formatting and returns the result.\n\n        :param str attr: The attribute/key to get from the object.\n        :param str obj: The object to access the attribute/key from.\n        :param callable accessor: Function used to access values from ``obj``.\n        :param dict kwargs: Field-specific keyword arguments.\n        \"\"\"\n        if self._CHECK_ATTRIBUTE:\n            value = self.get_value(obj, attr, accessor=accessor)\n            if value is missing_ and hasattr(self, \"default\"):\n                default = self.default\n                value = default() if callable(default) else default\n            if value is missing_:\n                return value\n        else:\n            value = None\n        return self._serialize(value, attr, obj, **kwargs)\n\n    def deserialize(self, value, attr=None, data=None, **kwargs):\n        \"\"\"Deserialize ``value``.\n\n        :param value: The value to deserialize.\n        :param str attr: The attribute/key in `data` to deserialize.\n        :param dict data: The raw input data passed to `Schema.load`.\n        :param dict kwargs: Field-specific keyword arguments.\n        :raise ValidationError: If an invalid value is passed or if a required value\n            is missing.\n        \"\"\"\n        # Validate required fields, deserialize, then validate\n        # deserialized value\n        self._validate_missing(value)\n        if value is missing_:\n            _miss = self.missing\n            return _miss() if callable(_miss) else _miss\n        if getattr(self, \"allow_none\", False) is True and value is None:\n            return None\n        output = self._deserialize(value, attr, data, **kwargs)\n        self._validate(output)\n        return output\n\n    # Methods for concrete classes to override.\n\n    def _bind_to_schema(self, field_name, schema):\n        \"\"\"Update field with values from its parent schema. Called by\n        :meth:`Schema._bind_field <marshmallow.Schema._bind_field>`.\n\n        :param str field_name: Field name set in schema.\n        :param Schema schema: Parent schema.\n        \"\"\"\n        self.parent = self.parent or schema\n        self.name = self.name or field_name\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        \"\"\"Serializes ``value`` to a basic Python datatype. Noop by default.\n        Concrete :class:`Field` classes should implement this method.\n\n        Example: ::\n\n            class TitleCase(Field):\n                def _serialize(self, value, attr, obj, **kwargs):\n                    if not value:\n                        return ''\n                    return str(value).title()\n\n        :param value: The value to be serialized.\n        :param str attr: The attribute or key on the object to be serialized.\n        :param object obj: The object the value was pulled from.\n        :param dict kwargs: Field-specific keyword arguments.\n        :return: The serialized value\n        \"\"\"\n        return value\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        \"\"\"Deserialize value. Concrete :class:`Field` classes should implement this method.\n\n        :param value: The value to be deserialized.\n        :param str attr: The attribute/key in `data` to be deserialized.\n        :param dict data: The raw input data passed to the `Schema.load`.\n        :param dict kwargs: Field-specific keyword arguments.\n        :raise ValidationError: In case of formatting or validation failure.\n        :return: The deserialized value.\n\n        .. versionchanged:: 2.0.0\n            Added ``attr`` and ``data`` parameters.\n\n        .. versionchanged:: 3.0.0\n            Added ``**kwargs`` to signature.\n        \"\"\"\n        return value\n\n    # Properties\n\n    @property\n    def context(self):\n        \"\"\"The context dictionary for the parent :class:`Schema`.\"\"\"\n        return self.parent.context\n\n    @property\n    def root(self):\n        \"\"\"Reference to the `Schema` that this field belongs to even if it is buried in a\n        container field (e.g. `List`).\n        Return `None` for unbound fields.\n        \"\"\"\n        ret = self\n        while hasattr(ret, \"parent\"):\n            ret = ret.parent\n        return ret if isinstance(ret, SchemaABC) else None\n\n\nclass Raw(Field):\n    \"\"\"Field that applies no formatting or validation.\"\"\"\n\n    pass\n\n\nclass Nested(Field):\n    \"\"\"Allows you to nest a :class:`Schema <marshmallow.Schema>`\n    inside a field.\n\n    Examples: ::\n\n        user = fields.Nested(UserSchema)\n        user2 = fields.Nested('UserSchema')  # Equivalent to above\n        collaborators = fields.Nested(UserSchema, many=True, only=('id',))\n        parent = fields.Nested('self')\n\n    When passing a `Schema <marshmallow.Schema>` instance as the first argument,\n    the instance's ``exclude``, ``only``, and ``many`` attributes will be respected.\n\n    Therefore, when passing the ``exclude``, ``only``, or ``many`` arguments to `fields.Nested`,\n    you should pass a `Schema <marshmallow.Schema>` class (not an instance) as the first argument.\n\n    ::\n\n        # Yes\n        author = fields.Nested(UserSchema, only=('id', 'name'))\n\n        # No\n        author = fields.Nested(UserSchema(), only=('id', 'name'))\n\n    :param Schema nested: The Schema class or class name (string)\n        to nest, or ``\"self\"`` to nest the :class:`Schema` within itself.\n    :param tuple exclude: A list or tuple of fields to exclude.\n    :param only: A list or tuple of fields to marshal. If `None`, all fields are marshalled.\n        This parameter takes precedence over ``exclude``.\n    :param bool many: Whether the field is a collection of objects.\n    :param unknown: Whether to exclude, include, or raise an error for unknown\n        fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n    \"\"\"\n\n    default_error_messages = {\"type\": \"Invalid type.\"}\n\n    def __init__(\n        self, nested, *, default=missing_, exclude=tuple(), only=None, **kwargs\n    ):\n        # Raise error if only or exclude is passed as string, not list of strings\n        if only is not None and not is_collection(only):\n            raise StringNotCollectionError('\"only\" should be a collection of strings.')\n        if exclude is not None and not is_collection(exclude):\n            raise StringNotCollectionError(\n                '\"exclude\" should be a collection of strings.'\n            )\n        self.nested = nested\n        self.only = only\n        self.exclude = exclude\n        self.many = kwargs.get(\"many\", False)\n        self.unknown = kwargs.get(\"unknown\")\n        self._schema = None  # Cached Schema instance\n        super().__init__(default=default, **kwargs)\n\n    @property\n    def schema(self):\n        \"\"\"The nested Schema object.\n\n        .. versionchanged:: 1.0.0\n            Renamed from `serializer` to `schema`.\n        \"\"\"\n        if not self._schema:\n            # Inherit context from parent.\n            context = getattr(self.parent, \"context\", {})\n            if isinstance(self.nested, SchemaABC):\n                self._schema = self.nested\n                self._schema.context.update(context)\n            else:\n                if isinstance(self.nested, type) and issubclass(self.nested, SchemaABC):\n                    schema_class = self.nested\n                elif not isinstance(self.nested, (str, bytes)):\n                    raise ValueError(\n                        \"Nested fields must be passed a \"\n                        \"Schema, not {}.\".format(self.nested.__class__)\n                    )\n                elif self.nested == \"self\":\n                    ret = self\n                    while not isinstance(ret, SchemaABC):\n                        ret = ret.parent\n                    schema_class = ret.__class__\n                else:\n                    schema_class = class_registry.get_class(self.nested)\n                self._schema = schema_class(\n                    many=self.many,\n                    only=self.only,\n                    exclude=self.exclude,\n                    context=context,\n                    load_only=self._nested_normalized_option(\"load_only\"),\n                    dump_only=self._nested_normalized_option(\"dump_only\"),\n                )\n        return self._schema\n\n    def _nested_normalized_option(self, option_name):\n        nested_field = \"%s.\" % self.name\n        return [\n            field.split(nested_field, 1)[1]\n            for field in getattr(self.root, option_name, set())\n            if field.startswith(nested_field)\n        ]\n\n    def _serialize(self, nested_obj, attr, obj, many=False, **kwargs):\n        # Load up the schema first. This allows a RegistryError to be raised\n        # if an invalid schema name was passed\n        schema = self.schema\n        if nested_obj is None:\n            return None\n        return schema.dump(nested_obj, many=self.many or many)\n\n    def _test_collection(self, value, many=False):\n        many = self.many or many\n        if many and not utils.is_collection(value):\n            raise self.make_error(\"type\", input=value, type=value.__class__.__name__)\n\n    def _load(self, value, data, partial=None, many=False):\n        try:\n            valid_data = self.schema.load(\n                value, unknown=self.unknown, partial=partial, many=self.many or many\n            )\n        except ValidationError as error:\n            raise ValidationError(\n                error.messages, valid_data=error.valid_data\n            ) from error\n        return valid_data\n\n    def _deserialize(self, value, attr, data, partial=None, many=False, **kwargs):\n        \"\"\"Same as :meth:`Field._deserialize` with additional ``partial`` argument.\n\n        :param bool|tuple partial: For nested schemas, the ``partial``\n            parameter passed to `Schema.load`.\n\n        .. versionchanged:: 3.0.0\n            Add ``partial`` parameter.\n        \"\"\"\n        self._test_collection(value, many=many)\n        return self._load(value, data, partial=partial, many=many)\n\n\nclass Pluck(Nested):\n    \"\"\"Allows you to replace nested data with one of the data's fields.\n\n    Example: ::\n\n        from marshmallow import Schema, fields\n\n        class ArtistSchema(Schema):\n            id = fields.Int()\n            name = fields.Str()\n\n        class AlbumSchema(Schema):\n            artist = fields.Pluck(ArtistSchema, 'id')\n\n\n        in_data = {'artist': 42}\n        loaded = AlbumSchema().load(in_data) # => {'artist': {'id': 42}}\n        dumped = AlbumSchema().dump(loaded)  # => {'artist': 42}\n\n    :param Schema nested: The Schema class or class name (string)\n        to nest, or ``\"self\"`` to nest the :class:`Schema` within itself.\n    :param str field_name: The key to pluck a value from.\n    :param kwargs: The same keyword arguments that :class:`Nested` receives.\n    \"\"\"\n\n    def __init__(self, nested, field_name, **kwargs):\n        super().__init__(nested, only=(field_name,), **kwargs)\n        self.field_name = field_name\n\n    @property\n    def _field_data_key(self):\n        only_field = self.schema.fields[self.field_name]\n        return only_field.data_key or self.field_name\n\n    def _serialize(self, nested_obj, attr, obj, **kwargs):\n        ret = super()._serialize(nested_obj, attr, obj, **kwargs)\n        if ret is None:\n            return None\n        if self.many:\n            return utils.pluck(ret, key=self._field_data_key)\n        return ret[self._field_data_key]\n\n    def _deserialize(self, value, attr, data, partial=None, **kwargs):\n        self._test_collection(value)\n        if self.many:\n            value = [{self._field_data_key: v} for v in value]\n        else:\n            value = {self._field_data_key: value}\n        return self._load(value, data, partial=partial)\n\n\nclass List(Field):\n    \"\"\"A list field, composed with another `Field` class or\n    instance.\n\n    Example: ::\n\n        numbers = fields.List(fields.Float())\n\n    :param Field cls_or_instance: A field class or instance.\n    :param bool default: Default value for serialization.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n\n    .. versionchanged:: 2.0.0\n        The ``allow_none`` parameter now applies to deserialization and\n        has the same semantics as the other fields.\n\n    .. versionchanged:: 3.0.0rc9\n        Does not serialize scalar values to single-item lists.\n    \"\"\"\n\n    default_error_messages = {\"invalid\": \"Not a valid list.\"}\n\n    def __init__(self, cls_or_instance, **kwargs):\n        super().__init__(**kwargs)\n        try:\n            self.inner = resolve_field_instance(cls_or_instance)\n        except FieldInstanceResolutionError as error:\n            raise ValueError(\n                \"The list elements must be a subclass or instance of \"\n                \"marshmallow.base.FieldABC.\"\n            ) from error\n        if isinstance(self.inner, Nested):\n            self.only = self.inner.only\n            self.exclude = self.inner.exclude\n\n    def _bind_to_schema(self, field_name, schema):\n        super()._bind_to_schema(field_name, schema)\n        self.inner = copy.deepcopy(self.inner)\n        self.inner._bind_to_schema(field_name, self)\n        if isinstance(self.inner, Nested):\n            self.inner.only = self.only\n            self.inner.exclude = self.exclude\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n        # Optimize dumping a list of Nested objects by calling dump(many=True)\n        if isinstance(self.inner, Nested) and not self.inner.many:\n            return self.inner._serialize(value, attr, obj, many=True, **kwargs)\n        return [self.inner._serialize(each, attr, obj, **kwargs) for each in value]\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if not utils.is_collection(value):\n            raise self.make_error(\"invalid\")\n        # Optimize loading a list of Nested objects by calling load(many=True)\n        if isinstance(self.inner, Nested) and not self.inner.many:\n            return self.inner.deserialize(value, many=True, **kwargs)\n\n        result = []\n        errors = {}\n        for idx, each in enumerate(value):\n            try:\n                result.append(self.inner.deserialize(each, **kwargs))\n            except ValidationError as error:\n                if error.valid_data is not None:\n                    result.append(error.valid_data)\n                errors.update({idx: error.messages})\n        if errors:\n            raise ValidationError(errors, valid_data=result)\n        return result\n\n\nclass Tuple(Field):\n    \"\"\"A tuple field, composed of a fixed number of other `Field` classes or\n    instances\n\n    Example: ::\n\n        row = Tuple((fields.String(), fields.Integer(), fields.Float()))\n\n    .. note::\n        Because of the structured nature of `collections.namedtuple` and\n        `typing.NamedTuple`, using a Schema within a Nested field for them is\n        more appropriate than using a `Tuple` field.\n\n    :param Iterable[Field] tuple_fields: An iterable of field classes or\n        instances.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n\n    .. versionadded:: 3.0.0rc4\n    \"\"\"\n\n    default_error_messages = {\"invalid\": \"Not a valid tuple.\"}\n\n    def __init__(self, tuple_fields, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        if not utils.is_collection(tuple_fields):\n            raise ValueError(\n                \"tuple_fields must be an iterable of Field classes or \" \"instances.\"\n            )\n\n        try:\n            self.tuple_fields = [\n                resolve_field_instance(cls_or_instance)\n                for cls_or_instance in tuple_fields\n            ]\n        except FieldInstanceResolutionError as error:\n            raise ValueError(\n                'Elements of \"tuple_fields\" must be subclasses or '\n                \"instances of marshmallow.base.FieldABC.\"\n            ) from error\n\n        self.validate_length = Length(equal=len(self.tuple_fields))\n\n    def _bind_to_schema(self, field_name, schema):\n        super()._bind_to_schema(field_name, schema)\n        new_tuple_fields = []\n        for field in self.tuple_fields:\n            field = copy.deepcopy(field)\n            field._bind_to_schema(field_name, self)\n            new_tuple_fields.append(field)\n\n        self.tuple_fields = new_tuple_fields\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n\n        return tuple(\n            field._serialize(each, attr, obj, **kwargs)\n            for field, each in zip(self.tuple_fields, value)\n        )\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if not utils.is_collection(value):\n            raise self.make_error(\"invalid\")\n\n        self.validate_length(value)\n\n        result = []\n        errors = {}\n\n        for idx, (field, each) in enumerate(zip(self.tuple_fields, value)):\n            try:\n                result.append(field.deserialize(each, **kwargs))\n            except ValidationError as error:\n                if error.valid_data is not None:\n                    result.append(error.valid_data)\n                errors.update({idx: error.messages})\n        if errors:\n            raise ValidationError(errors, valid_data=result)\n\n        return tuple(result)\n\n\nclass String(Field):\n    \"\"\"A string field.\n\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n    \"\"\"\n\n    default_error_messages = {\n        \"invalid\": \"Not a valid string.\",\n        \"invalid_utf8\": \"Not a valid utf-8 string.\",\n    }\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n        return utils.ensure_text_type(value)\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if not isinstance(value, (str, bytes)):\n            raise self.make_error(\"invalid\")\n        try:\n            return utils.ensure_text_type(value)\n        except UnicodeDecodeError as error:\n            raise self.make_error(\"invalid_utf8\") from error\n\n\nclass UUID(String):\n    \"\"\"A UUID field.\"\"\"\n\n    default_error_messages = {\"invalid_uuid\": \"Not a valid UUID.\"}\n\n    def _validated(self, value):\n        \"\"\"Format the value or raise a :exc:`ValidationError` if an error occurs.\"\"\"\n        if value is None:\n            return None\n        if isinstance(value, uuid.UUID):\n            return value\n        try:\n            if isinstance(value, bytes) and len(value) == 16:\n                return uuid.UUID(bytes=value)\n            else:\n                return uuid.UUID(value)\n        except (ValueError, AttributeError, TypeError) as error:\n            raise self.make_error(\"invalid_uuid\") from error\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        val = str(value) if value is not None else None\n        return super()._serialize(val, attr, obj, **kwargs)\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        return self._validated(value)\n\n\nclass Number(Field):\n    \"\"\"Base class for number fields.\n\n    :param bool as_string: If True, format the serialized value as a string.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n    \"\"\"\n\n    num_type = float\n    default_error_messages = {\n        \"invalid\": \"Not a valid number.\",\n        \"too_large\": \"Number too large.\",\n    }\n\n    def __init__(self, *, as_string=False, **kwargs):\n        self.as_string = as_string\n        super().__init__(**kwargs)\n\n    def _format_num(self, value):\n        \"\"\"Return the number value for value, given this field's `num_type`.\"\"\"\n        return self.num_type(value)\n\n    def _validated(self, value):\n        \"\"\"Format the value or raise a :exc:`ValidationError` if an error occurs.\"\"\"\n        if value is None:\n            return None\n        # (value is True or value is False) is ~5x faster than isinstance(value, bool)\n        if value is True or value is False:\n            raise self.make_error(\"invalid\", input=value)\n        try:\n            return self._format_num(value)\n        except (TypeError, ValueError) as error:\n            raise self.make_error(\"invalid\", input=value) from error\n        except OverflowError as error:\n            raise self.make_error(\"too_large\", input=value) from error\n\n    def _to_string(self, value):\n        return str(value)\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        \"\"\"Return a string if `self.as_string=True`, otherwise return this field's `num_type`.\"\"\"\n        if value is None:\n            return None\n        ret = self._format_num(value)\n        return self._to_string(ret) if self.as_string else ret\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        return self._validated(value)\n\n\nclass Integer(Number):\n    \"\"\"An integer field.\n\n    :param kwargs: The same keyword arguments that :class:`Number` receives.\n    \"\"\"\n\n    num_type = int\n    default_error_messages = {\"invalid\": \"Not a valid integer.\"}\n\n    def __init__(self, *, strict=False, **kwargs):\n        self.strict = strict\n        super().__init__(**kwargs)\n\n    # override Number\n    def _validated(self, value):\n        if self.strict:\n            if isinstance(value, numbers.Number) and isinstance(\n                value, numbers.Integral\n            ):\n                return super()._validated(value)\n            raise self.make_error(\"invalid\", input=value)\n        return super()._validated(value)\n\n\nclass Float(Number):\n    \"\"\"A double as an IEEE-754 double precision string.\n\n    :param bool allow_nan: If `True`, `NaN`, `Infinity` and `-Infinity` are allowed,\n        even though they are illegal according to the JSON specification.\n    :param bool as_string: If True, format the value as a string.\n    :param kwargs: The same keyword arguments that :class:`Number` receives.\n    \"\"\"\n\n    num_type = float\n    default_error_messages = {\n        \"special\": \"Special numeric values (nan or infinity) are not permitted.\"\n    }\n\n    def __init__(self, *, allow_nan=False, as_string=False, **kwargs):\n        self.allow_nan = allow_nan\n        super().__init__(as_string=as_string, **kwargs)\n\n    def _validated(self, value):\n        num = super()._validated(value)\n        if self.allow_nan is False:\n            if math.isnan(num) or num == float(\"inf\") or num == float(\"-inf\"):\n                raise self.make_error(\"special\")\n        return num\n\n\nclass Decimal(Number):\n    \"\"\"A field that (de)serializes to the Python ``decimal.Decimal`` type.\n    It's safe to use when dealing with money values, percentages, ratios\n    or other numbers where precision is critical.\n\n    .. warning::\n\n        This field serializes to a `decimal.Decimal` object by default. If you need\n        to render your data as JSON, keep in mind that the `json` module from the\n        standard library does not encode `decimal.Decimal`. Therefore, you must use\n        a JSON library that can handle decimals, such as `simplejson`, or serialize\n        to a string by passing ``as_string=True``.\n\n    .. warning::\n\n        If a JSON `float` value is passed to this field for deserialization it will\n        first be cast to its corresponding `string` value before being deserialized\n        to a `decimal.Decimal` object. The default `__str__` implementation of the\n        built-in Python `float` type may apply a destructive transformation upon\n        its input data and therefore cannot be relied upon to preserve precision.\n        To avoid this, you can instead pass a JSON `string` to be deserialized\n        directly.\n\n    :param int places: How many decimal places to quantize the value. If `None`, does\n        not quantize the value.\n    :param rounding: How to round the value during quantize, for example\n        `decimal.ROUND_UP`. If None, uses the rounding value from\n        the current thread's context.\n    :param bool allow_nan: If `True`, `NaN`, `Infinity` and `-Infinity` are allowed,\n        even though they are illegal according to the JSON specification.\n    :param bool as_string: If True, serialize to a string instead of a Python\n        `decimal.Decimal` type.\n    :param kwargs: The same keyword arguments that :class:`Number` receives.\n\n    .. versionadded:: 1.2.0\n    \"\"\"\n\n    num_type = decimal.Decimal\n\n    default_error_messages = {\n        \"special\": \"Special numeric values (nan or infinity) are not permitted.\"\n    }\n\n    def __init__(\n        self, places=None, rounding=None, *, allow_nan=False, as_string=False, **kwargs\n    ):\n        self.places = (\n            decimal.Decimal((0, (1,), -places)) if places is not None else None\n        )\n        self.rounding = rounding\n        self.allow_nan = allow_nan\n        super().__init__(as_string=as_string, **kwargs)\n\n    # override Number\n    def _format_num(self, value):\n        num = decimal.Decimal(str(value))\n        if self.allow_nan:\n            if num.is_nan():\n                return decimal.Decimal(\"NaN\")  # avoid sNaN, -sNaN and -NaN\n        if self.places is not None and num.is_finite():\n            num = num.quantize(self.places, rounding=self.rounding)\n        return num\n\n    # override Number\n    def _validated(self, value):\n        try:\n            num = super()._validated(value)\n        except decimal.InvalidOperation as error:\n            raise self.make_error(\"invalid\") from error\n        if not self.allow_nan and (num.is_nan() or num.is_infinite()):\n            raise self.make_error(\"special\")\n        return num\n\n    # override Number\n    def _to_string(self, value):\n        return format(value, \"f\")\n\n\nclass Boolean(Field):\n    \"\"\"A boolean field.\n\n    :param set truthy: Values that will (de)serialize to `True`. If an empty\n        set, any non-falsy value will deserialize to `True`. If `None`,\n        `marshmallow.fields.Boolean.truthy` will be used.\n    :param set falsy: Values that will (de)serialize to `False`. If `None`,\n        `marshmallow.fields.Boolean.falsy` will be used.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n    \"\"\"\n\n    #: Default truthy values.\n    truthy = {\n        \"t\",\n        \"T\",\n        \"true\",\n        \"True\",\n        \"TRUE\",\n        \"on\",\n        \"On\",\n        \"ON\",\n        \"y\",\n        \"Y\",\n        \"yes\",\n        \"Yes\",\n        \"YES\",\n        \"1\",\n        1,\n        True,\n    }\n    #: Default falsy values.\n    falsy = {\n        \"f\",\n        \"F\",\n        \"false\",\n        \"False\",\n        \"FALSE\",\n        \"off\",\n        \"Off\",\n        \"OFF\",\n        \"n\",\n        \"N\",\n        \"no\",\n        \"No\",\n        \"NO\",\n        \"0\",\n        0,\n        0.0,\n        False,\n    }\n\n    default_error_messages = {\"invalid\": \"Not a valid boolean.\"}\n\n    def __init__(self, *, truthy=None, falsy=None, **kwargs):\n        super().__init__(**kwargs)\n\n        if truthy is not None:\n            self.truthy = set(truthy)\n        if falsy is not None:\n            self.falsy = set(falsy)\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n        elif value in self.truthy:\n            return True\n        elif value in self.falsy:\n            return False\n\n        return bool(value)\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if not self.truthy:\n            return bool(value)\n        else:\n            try:\n                if value in self.truthy:\n                    return True\n                elif value in self.falsy:\n                    return False\n            except TypeError as error:\n                raise self.make_error(\"invalid\", input=value) from error\n        raise self.make_error(\"invalid\", input=value)\n\n\nclass DateTime(Field):\n    \"\"\"A formatted datetime string.\n\n    Example: ``'2014-12-22T03:12:58.019077+00:00'``\n\n    :param str format: Either ``\"rfc\"`` (for RFC822), ``\"iso\"`` (for ISO8601),\n        or a date format string. If `None`, defaults to \"iso\".\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n\n    .. versionchanged:: 3.0.0rc9\n        Does not modify timezone information on (de)serialization.\n    \"\"\"\n\n    SERIALIZATION_FUNCS = {\n        \"iso\": utils.isoformat,\n        \"iso8601\": utils.isoformat,\n        \"rfc\": utils.rfcformat,\n        \"rfc822\": utils.rfcformat,\n    }\n\n    DESERIALIZATION_FUNCS = {\n        \"iso\": utils.from_iso_datetime,\n        \"iso8601\": utils.from_iso_datetime,\n        \"rfc\": utils.from_rfc,\n        \"rfc822\": utils.from_rfc,\n    }\n\n    DEFAULT_FORMAT = \"iso\"\n\n    OBJ_TYPE = \"datetime\"\n\n    SCHEMA_OPTS_VAR_NAME = \"datetimeformat\"\n\n    default_error_messages = {\n        \"invalid\": \"Not a valid {obj_type}.\",\n        \"invalid_awareness\": \"Not a valid {awareness} {obj_type}.\",\n        \"format\": '\"{input}\" cannot be formatted as a {obj_type}.',\n    }\n\n    def __init__(self, format=None, **kwargs):\n        super().__init__(**kwargs)\n        # Allow this to be None. It may be set later in the ``_serialize``\n        # or ``_deserialize`` methods. This allows a Schema to dynamically set the\n        # format, e.g. from a Meta option\n        self.format = format\n\n    def _bind_to_schema(self, field_name, schema):\n        super()._bind_to_schema(field_name, schema)\n        self.format = (\n            self.format\n            or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME)\n            or self.DEFAULT_FORMAT\n        )\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n        data_format = self.format or self.DEFAULT_FORMAT\n        format_func = self.SERIALIZATION_FUNCS.get(data_format)\n        if format_func:\n            return format_func(value)\n        else:\n            return value.strftime(data_format)\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if not value:  # Falsy values, e.g. '', None, [] are not valid\n            raise self.make_error(\"invalid\", input=value, obj_type=self.OBJ_TYPE)\n        data_format = self.format or self.DEFAULT_FORMAT\n        func = self.DESERIALIZATION_FUNCS.get(data_format)\n        if func:\n            try:\n                return func(value)\n            except (TypeError, AttributeError, ValueError) as error:\n                raise self.make_error(\n                    \"invalid\", input=value, obj_type=self.OBJ_TYPE\n                ) from error\n        else:\n            try:\n                return self._make_object_from_format(value, data_format)\n            except (TypeError, AttributeError, ValueError) as error:\n                raise self.make_error(\n                    \"invalid\", input=value, obj_type=self.OBJ_TYPE\n                ) from error\n\n    @staticmethod\n    def _make_object_from_format(value, data_format):\n        return dt.datetime.strptime(value, data_format)\n\n\nclass NaiveDateTime(DateTime):\n    \"\"\"A formatted naive datetime string.\n\n    :param str format: See :class:`DateTime`.\n    :param timezone timezone: Used on deserialization. If `None`,\n        aware datetimes are rejected. If not `None`, aware datetimes are\n        converted to this timezone before their timezone information is\n        removed.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n\n    .. versionadded:: 3.0.0rc9\n    \"\"\"\n\n    AWARENESS = \"naive\"\n\n    def __init__(self, format=None, *, timezone=None, **kwargs):\n        super().__init__(format=format, **kwargs)\n        self.timezone = timezone\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        ret = super()._deserialize(value, attr, data, **kwargs)\n        if is_aware(ret):\n            if self.timezone is None:\n                raise self.make_error(\n                    \"invalid_awareness\",\n                    awareness=self.AWARENESS,\n                    obj_type=self.OBJ_TYPE,\n                )\n            ret = ret.astimezone(self.timezone).replace(tzinfo=None)\n        return ret\n\n\nclass AwareDateTime(DateTime):\n    \"\"\"A formatted aware datetime string.\n\n    :param str format: See :class:`DateTime`.\n    :param timezone default_timezone: Used on deserialization. If `None`, naive\n        datetimes are rejected. If not `None`, naive datetimes are set this\n        timezone.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n\n    .. versionadded:: 3.0.0rc9\n    \"\"\"\n\n    AWARENESS = \"aware\"\n\n    def __init__(self, format=None, *, default_timezone=None, **kwargs):\n        super().__init__(format=format, **kwargs)\n        self.default_timezone = default_timezone\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        ret = super()._deserialize(value, attr, data, **kwargs)\n        if not is_aware(ret):\n            if self.default_timezone is None:\n                raise self.make_error(\n                    \"invalid_awareness\",\n                    awareness=self.AWARENESS,\n                    obj_type=self.OBJ_TYPE,\n                )\n            ret = ret.replace(tzinfo=self.default_timezone)\n        return ret\n\n\nclass Time(Field):\n    \"\"\"ISO8601-formatted time string.\n\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n    \"\"\"\n\n    default_error_messages = {\n        \"invalid\": \"Not a valid time.\",\n        \"format\": '\"{input}\" cannot be formatted as a time.',\n    }\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n        ret = value.isoformat()\n        if value.microsecond:\n            return ret[:15]\n        return ret\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        \"\"\"Deserialize an ISO8601-formatted time to a :class:`datetime.time` object.\"\"\"\n        if not value:  # falsy values are invalid\n            raise self.make_error(\"invalid\")\n        try:\n            return utils.from_iso_time(value)\n        except (AttributeError, TypeError, ValueError) as error:\n            raise self.make_error(\"invalid\") from error\n\n\nclass Date(DateTime):\n    \"\"\"ISO8601-formatted date string.\n\n    :param format: Either ``\"iso\"`` (for ISO8601) or a date format string.\n        If `None`, defaults to \"iso\".\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n    \"\"\"\n\n    default_error_messages = {\n        \"invalid\": \"Not a valid date.\",\n        \"format\": '\"{input}\" cannot be formatted as a date.',\n    }\n\n    SERIALIZATION_FUNCS = {\"iso\": utils.to_iso_date, \"iso8601\": utils.to_iso_date}\n\n    DESERIALIZATION_FUNCS = {\"iso\": utils.from_iso_date, \"iso8601\": utils.from_iso_date}\n\n    DEFAULT_FORMAT = \"iso\"\n\n    OBJ_TYPE = \"date\"\n\n    SCHEMA_OPTS_VAR_NAME = \"dateformat\"\n\n    @staticmethod\n    def _make_object_from_format(value, data_format):\n        return dt.datetime.strptime(value, data_format).date()\n\n\nclass TimeDelta(Field):\n    \"\"\"A field that (de)serializes a :class:`datetime.timedelta` object to an\n    integer and vice versa. The integer can represent the number of days,\n    seconds or microseconds.\n\n    :param str precision: Influences how the integer is interpreted during\n        (de)serialization. Must be 'days', 'seconds', 'microseconds',\n        'milliseconds', 'minutes', 'hours' or 'weeks'.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n\n    .. versionchanged:: 2.0.0\n        Always serializes to an integer value to avoid rounding errors.\n        Add `precision` parameter.\n    \"\"\"\n\n    DAYS = \"days\"\n    SECONDS = \"seconds\"\n    MICROSECONDS = \"microseconds\"\n    MILLISECONDS = \"milliseconds\"\n    MINUTES = \"minutes\"\n    HOURS = \"hours\"\n    WEEKS = \"weeks\"\n\n    default_error_messages = {\n        \"invalid\": \"Not a valid period of time.\",\n        \"format\": \"{input!r} cannot be formatted as a timedelta.\",\n    }\n\n    def __init__(self, precision=SECONDS, **kwargs):\n        precision = precision.lower()\n        units = (\n            self.DAYS,\n            self.SECONDS,\n            self.MICROSECONDS,\n            self.MILLISECONDS,\n            self.MINUTES,\n            self.HOURS,\n            self.WEEKS,\n        )\n\n        if precision not in units:\n            msg = 'The precision must be {} or \"{}\".'.format(\n                \", \".join(['\"{}\"'.format(each) for each in units[:-1]]), units[-1]\n            )\n            raise ValueError(msg)\n\n        self.precision = precision\n        super().__init__(**kwargs)\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n        base_unit = dt.timedelta(**{self.precision: 1})\n        return int(value.total_seconds() / base_unit.total_seconds())\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        try:\n            value = int(value)\n        except (TypeError, ValueError) as error:\n            raise self.make_error(\"invalid\") from error\n\n        kwargs = {self.precision: value}\n\n        try:\n            return dt.timedelta(**kwargs)\n        except OverflowError as error:\n            raise self.make_error(\"invalid\") from error\n\n\nclass Mapping(Field):\n    \"\"\"An abstract class for objects with key-value pairs.\n\n    :param Field keys: A field class or instance for dict keys.\n    :param Field values: A field class or instance for dict values.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n\n    .. note::\n        When the structure of nested data is not known, you may omit the\n        `keys` and `values` arguments to prevent content validation.\n\n    .. versionadded:: 3.0.0rc4\n    \"\"\"\n\n    mapping_type = dict\n    default_error_messages = {\"invalid\": \"Not a valid mapping type.\"}\n\n    def __init__(self, keys=None, values=None, **kwargs):\n        super().__init__(**kwargs)\n        if keys is None:\n            self.key_field = None\n        else:\n            try:\n                self.key_field = resolve_field_instance(keys)\n            except FieldInstanceResolutionError as error:\n                raise ValueError(\n                    '\"keys\" must be a subclass or instance of '\n                    \"marshmallow.base.FieldABC.\"\n                ) from error\n\n        if values is None:\n            self.value_field = None\n        else:\n            try:\n                self.value_field = resolve_field_instance(values)\n            except FieldInstanceResolutionError as error:\n                raise ValueError(\n                    '\"values\" must be a subclass or instance of '\n                    \"marshmallow.base.FieldABC.\"\n                ) from error\n            if isinstance(self.value_field, Nested):\n                self.only = self.value_field.only\n                self.exclude = self.value_field.exclude\n\n    def _bind_to_schema(self, field_name, schema):\n        super()._bind_to_schema(field_name, schema)\n        if self.value_field:\n            self.value_field = copy.deepcopy(self.value_field)\n            self.value_field._bind_to_schema(field_name, self)\n        if isinstance(self.value_field, Nested):\n            self.value_field.only = self.only\n            self.value_field.exclude = self.exclude\n        if self.key_field:\n            self.key_field = copy.deepcopy(self.key_field)\n            self.key_field._bind_to_schema(field_name, self)\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n        if not self.value_field and not self.key_field:\n            return value\n\n        #  Serialize keys\n        if self.key_field is None:\n            keys = {k: k for k in value.keys()}\n        else:\n            keys = {\n                k: self.key_field._serialize(k, None, None, **kwargs)\n                for k in value.keys()\n            }\n\n        #  Serialize values\n        result = self.mapping_type()\n        if self.value_field is None:\n            for k, v in value.items():\n                if k in keys:\n                    result[keys[k]] = v\n        else:\n            for k, v in value.items():\n                result[keys[k]] = self.value_field._serialize(v, None, None, **kwargs)\n\n        return result\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if not isinstance(value, _Mapping):\n            raise self.make_error(\"invalid\")\n        if not self.value_field and not self.key_field:\n            return value\n\n        errors = collections.defaultdict(dict)\n\n        #  Deserialize keys\n        if self.key_field is None:\n            keys = {k: k for k in value.keys()}\n        else:\n            keys = {}\n            for key in value.keys():\n                try:\n                    keys[key] = self.key_field.deserialize(key, **kwargs)\n                except ValidationError as error:\n                    errors[key][\"key\"] = error.messages\n\n        #  Deserialize values\n        result = self.mapping_type()\n        if self.value_field is None:\n            for k, v in value.items():\n                if k in keys:\n                    result[keys[k]] = v\n        else:\n            for key, val in value.items():\n                try:\n                    deser_val = self.value_field.deserialize(val, **kwargs)\n                except ValidationError as error:\n                    errors[key][\"value\"] = error.messages\n                    if error.valid_data is not None and key in keys:\n                        result[keys[key]] = error.valid_data\n                else:\n                    if key in keys:\n                        result[keys[key]] = deser_val\n\n        if errors:\n            raise ValidationError(errors, valid_data=result)\n\n        return result\n\n\nclass Dict(Mapping):\n    \"\"\"A dict field. Supports dicts and dict-like objects. Extends\n    Mapping with dict as the mapping_type.\n\n    Example: ::\n\n        numbers = fields.Dict(keys=fields.Str(), values=fields.Float())\n\n    :param kwargs: The same keyword arguments that :class:`Mapping` receives.\n\n    .. versionadded:: 2.1.0\n    \"\"\"\n\n    mapping_type = dict\n\n\nclass Url(String):\n    \"\"\"A validated URL field. Validation occurs during both serialization and\n    deserialization.\n\n    :param default: Default value for the field if the attribute is not set.\n    :param str attribute: The name of the attribute to get the value from. If\n        `None`, assumes the attribute has the same name as the field.\n    :param bool relative: Whether to allow relative URLs.\n    :param bool require_tld: Whether to reject non-FQDN hostnames.\n    :param kwargs: The same keyword arguments that :class:`String` receives.\n    \"\"\"\n\n    default_error_messages = {\"invalid\": \"Not a valid URL.\"}\n\n    def __init__(self, *, relative=False, schemes=None, require_tld=True, **kwargs):\n        super().__init__(**kwargs)\n\n        self.relative = relative\n        self.require_tld = require_tld\n        # Insert validation into self.validators so that multiple errors can be\n        # stored.\n        self.validators.insert(\n            0,\n            validate.URL(\n                relative=self.relative,\n                schemes=schemes,\n                require_tld=self.require_tld,\n                error=self.error_messages[\"invalid\"],\n            ),\n        )\n\n\nclass Email(String):\n    \"\"\"A validated email field. Validation occurs during both serialization and\n    deserialization.\n\n    :param args: The same positional arguments that :class:`String` receives.\n    :param kwargs: The same keyword arguments that :class:`String` receives.\n    \"\"\"\n\n    default_error_messages = {\"invalid\": \"Not a valid email address.\"}\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        # Insert validation into self.validators so that multiple errors can be\n        # stored.\n        self.validators.insert(0, validate.Email(error=self.error_messages[\"invalid\"]))\n\n\nclass Method(Field):\n    \"\"\"A field that takes the value returned by a `Schema` method.\n\n    :param str serialize: The name of the Schema method from which\n        to retrieve the value. The method must take an argument ``obj``\n        (in addition to self) that is the object to be serialized.\n    :param str deserialize: Optional name of the Schema method for deserializing\n        a value The method must take a single argument ``value``, which is the\n        value to deserialize.\n\n    .. versionchanged:: 2.0.0\n        Removed optional ``context`` parameter on methods. Use ``self.context`` instead.\n\n    .. versionchanged:: 2.3.0\n        Deprecated ``method_name`` parameter in favor of ``serialize`` and allow\n        ``serialize`` to not be passed at all.\n\n    .. versionchanged:: 3.0.0\n        Removed ``method_name`` parameter.\n    \"\"\"\n\n    _CHECK_ATTRIBUTE = False\n\n    def __init__(self, serialize=None, deserialize=None, **kwargs):\n        # Set dump_only and load_only based on arguments\n        kwargs[\"dump_only\"] = bool(serialize) and not bool(deserialize)\n        kwargs[\"load_only\"] = bool(deserialize) and not bool(serialize)\n        super().__init__(**kwargs)\n        self.serialize_method_name = serialize\n        self.deserialize_method_name = deserialize\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if not self.serialize_method_name:\n            return missing_\n\n        method = utils.callable_or_raise(\n            getattr(self.parent, self.serialize_method_name, None)\n        )\n        return method(obj)\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if self.deserialize_method_name:\n            method = utils.callable_or_raise(\n                getattr(self.parent, self.deserialize_method_name, None)\n            )\n            return method(value)\n        return value\n\n\nclass Function(Field):\n    \"\"\"A field that takes the value returned by a function.\n\n    :param callable serialize: A callable from which to retrieve the value.\n        The function must take a single argument ``obj`` which is the object\n        to be serialized. It can also optionally take a ``context`` argument,\n        which is a dictionary of context variables passed to the serializer.\n        If no callable is provided then the ```load_only``` flag will be set\n        to True.\n    :param callable deserialize: A callable from which to retrieve the value.\n        The function must take a single argument ``value`` which is the value\n        to be deserialized. It can also optionally take a ``context`` argument,\n        which is a dictionary of context variables passed to the deserializer.\n        If no callable is provided then ```value``` will be passed through\n        unchanged.\n\n    .. versionchanged:: 2.3.0\n        Deprecated ``func`` parameter in favor of ``serialize``.\n\n    .. versionchanged:: 3.0.0a1\n        Removed ``func`` parameter.\n    \"\"\"\n\n    _CHECK_ATTRIBUTE = False\n\n    def __init__(self, serialize=None, deserialize=None, **kwargs):\n        # Set dump_only and load_only based on arguments\n        kwargs[\"dump_only\"] = bool(serialize) and not bool(deserialize)\n        kwargs[\"load_only\"] = bool(deserialize) and not bool(serialize)\n        super().__init__(**kwargs)\n        self.serialize_func = serialize and utils.callable_or_raise(serialize)\n        self.deserialize_func = deserialize and utils.callable_or_raise(deserialize)\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        return self._call_or_raise(self.serialize_func, obj, attr)\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if self.deserialize_func:\n            return self._call_or_raise(self.deserialize_func, value, attr)\n        return value\n\n    def _call_or_raise(self, func, value, attr):\n        if len(utils.get_func_args(func)) > 1:\n            if self.parent.context is None:\n                msg = \"No context available for Function field {!r}\".format(attr)\n                raise ValidationError(msg)\n            return func(value, self.parent.context)\n        else:\n            return func(value)\n\n\nclass Constant(Field):\n    \"\"\"A field that (de)serializes to a preset constant.  If you only want the\n    constant added for serialization or deserialization, you should use\n    ``dump_only=True`` or ``load_only=True`` respectively.\n\n    :param constant: The constant to return for the field attribute.\n\n    .. versionadded:: 2.0.0\n    \"\"\"\n\n    _CHECK_ATTRIBUTE = False\n\n    def __init__(self, constant, **kwargs):\n        super().__init__(**kwargs)\n        self.constant = constant\n        self.missing = constant\n        self.default = constant\n\n    def _serialize(self, value, *args, **kwargs):\n        return self.constant\n\n    def _deserialize(self, value, *args, **kwargs):\n        return self.constant\n\n\nclass Inferred(Field):\n    \"\"\"A field that infers how to serialize, based on the value type.\n\n    .. warning::\n\n        This class is treated as private API.\n        Users should not need to use this class directly.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        # We memoize the fields to avoid creating and binding new fields\n        # every time on serialization.\n        self._field_cache = {}\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        field_cls = self.root.TYPE_MAPPING.get(type(value))\n        if field_cls is None:\n            field = super()\n        else:\n            field = self._field_cache.get(field_cls)\n            if field is None:\n                field = field_cls()\n                field._bind_to_schema(self.name, self.parent)\n                self._field_cache[field_cls] = field\n        return field._serialize(value, attr, obj, **kwargs)\n\n\n# Aliases\nURL = Url\nStr = String\nBool = Boolean\nInt = Integer\n","new_file_content":"\"\"\"Field classes for various types of data.\"\"\"\n\nimport collections\nimport copy\nimport datetime as dt\nimport numbers\nimport uuid\nimport decimal\nimport math\nimport warnings\nfrom collections.abc import Mapping as _Mapping\n\nfrom marshmallow import validate, utils, class_registry\nfrom marshmallow.base import FieldABC, SchemaABC\nfrom marshmallow.utils import (\n    is_collection,\n    missing as missing_,\n    resolve_field_instance,\n    is_aware,\n)\nfrom marshmallow.exceptions import (\n    ValidationError,\n    StringNotCollectionError,\n    FieldInstanceResolutionError,\n)\nfrom marshmallow.validate import Validator, Length\n\n__all__ = [\n    \"Field\",\n    \"Raw\",\n    \"Nested\",\n    \"Mapping\",\n    \"Dict\",\n    \"List\",\n    \"Tuple\",\n    \"String\",\n    \"UUID\",\n    \"Number\",\n    \"Integer\",\n    \"Decimal\",\n    \"Boolean\",\n    \"Float\",\n    \"DateTime\",\n    \"NaiveDateTime\",\n    \"AwareDateTime\",\n    \"Time\",\n    \"Date\",\n    \"TimeDelta\",\n    \"Url\",\n    \"URL\",\n    \"Email\",\n    \"Method\",\n    \"Function\",\n    \"Str\",\n    \"Bool\",\n    \"Int\",\n    \"Constant\",\n    \"Pluck\",\n]\n\nMISSING_ERROR_MESSAGE = (\n    \"ValidationError raised by `{class_name}`, but error key `{key}` does \"\n    \"not exist in the `error_messages` dictionary.\"\n)\n\n\nclass Field(FieldABC):\n    \"\"\"Basic field from which other fields should extend. It applies no\n    formatting by default, and should only be used in cases where\n    data does not need to be formatted before being serialized or deserialized.\n    On error, the name of the field will be returned.\n\n    :param default: If set, this value will be used during serialization if the input value\n        is missing. If not set, the field will be excluded from the serialized output if the\n        input value is missing. May be a value or a callable.\n    :param missing: Default deserialization value for the field if the field is not\n        found in the input data. May be a value or a callable.\n    :param str data_key: The name of the dict key in the external representation, i.e.\n        the input of `load` and the output of `dump`.\n        If `None`, the key will match the name of the field.\n    :param str attribute: The name of the attribute to get the value from when serializing.\n        If `None`, assumes the attribute has the same name as the field.\n        Note: This should only be used for very specific use cases such as\n        outputting multiple fields for a single attribute. In most cases,\n        you should use ``data_key`` instead.\n    :param callable validate: Validator or collection of validators that are called\n        during deserialization. Validator takes a field's input value as\n        its only parameter and returns a boolean.\n        If it returns `False`, an :exc:`ValidationError` is raised.\n    :param required: Raise a :exc:`ValidationError` if the field value\n        is not supplied during deserialization.\n    :param allow_none: Set this to `True` if `None` should be considered a valid value during\n        validation/deserialization. If ``missing=None`` and ``allow_none`` is unset,\n        will default to ``True``. Otherwise, the default is ``False``.\n    :param bool load_only: If `True` skip this field during serialization, otherwise\n        its value will be present in the serialized data.\n    :param bool dump_only: If `True` skip this field during deserialization, otherwise\n        its value will be present in the deserialized object. In the context of an\n        HTTP API, this effectively marks the field as \"read-only\".\n    :param dict error_messages: Overrides for `Field.default_error_messages`.\n    :param metadata: Extra arguments to be stored as metadata.\n\n    .. versionchanged:: 2.0.0\n        Removed `error` parameter. Use ``error_messages`` instead.\n\n    .. versionchanged:: 2.0.0\n        Added `allow_none` parameter, which makes validation/deserialization of `None`\n        consistent across fields.\n\n    .. versionchanged:: 2.0.0\n        Added `load_only` and `dump_only` parameters, which allow field skipping\n        during the (de)serialization process.\n\n    .. versionchanged:: 2.0.0\n        Added `missing` parameter, which indicates the value for a field if the field\n        is not found during deserialization.\n\n    .. versionchanged:: 2.0.0\n        ``default`` value is only used if explicitly set. Otherwise, missing values\n        inputs are excluded from serialized output.\n\n    .. versionchanged:: 3.0.0b8\n        Add ``data_key`` parameter for the specifying the key in the input and\n        output data. This parameter replaced both ``load_from`` and ``dump_to``.\n    \"\"\"\n\n    # Some fields, such as Method fields and Function fields, are not expected\n    #  to exist as attributes on the objects to serialize. Set this to False\n    #  for those fields\n    _CHECK_ATTRIBUTE = True\n    _creation_index = 0  # Used for sorting\n\n    #: Default error messages for various kinds of errors. The keys in this dictionary\n    #: are passed to `Field.fail`. The values are error messages passed to\n    #: :exc:`marshmallow.exceptions.ValidationError`.\n    default_error_messages = {\n        \"required\": \"Missing data for required field.\",\n        \"null\": \"Field may not be null.\",\n        \"validator_failed\": \"Invalid value.\",\n    }\n\n    def __init__(\n        self,\n        *,\n        default=missing_,\n        missing=missing_,\n        data_key=None,\n        attribute=None,\n        validate=None,\n        required=False,\n        allow_none=None,\n        load_only=False,\n        dump_only=False,\n        error_messages=None,\n        **metadata\n    ):\n        self.default = default\n        self.attribute = attribute\n        self.data_key = data_key\n        self.validate = validate\n        if utils.is_iterable_but_not_string(validate):\n            if not utils.is_generator(validate):\n                self.validators = validate\n            else:\n                self.validators = list(validate)\n        elif callable(validate):\n            self.validators = [validate]\n        elif validate is None:\n            self.validators = []\n        else:\n            raise ValueError(\n                \"The 'validate' parameter must be a callable \"\n                \"or a collection of callables.\"\n            )\n\n        # If missing=None, None should be considered valid by default\n        if allow_none is None:\n            if missing is None:\n                self.allow_none = True\n            else:\n                self.allow_none = False\n        else:\n            self.allow_none = allow_none\n        self.load_only = load_only\n        self.dump_only = dump_only\n        if required is True and missing is not missing_:\n            raise ValueError(\"'missing' must not be set for required fields.\")\n        self.required = required\n        self.missing = missing\n        self.metadata = metadata\n        self._creation_index = Field._creation_index\n        Field._creation_index += 1\n\n        # Collect default error message from self and parent classes\n        messages = {}\n        for cls in reversed(self.__class__.__mro__):\n            messages.update(getattr(cls, \"default_error_messages\", {}))\n        messages.update(error_messages or {})\n        self.error_messages = messages\n\n    def __repr__(self):\n        return (\n            \"<fields.{ClassName}(default={self.default!r}, \"\n            \"attribute={self.attribute!r}, \"\n            \"validate={self.validate}, required={self.required}, \"\n            \"load_only={self.load_only}, dump_only={self.dump_only}, \"\n            \"missing={self.missing}, allow_none={self.allow_none}, \"\n            \"error_messages={self.error_messages})>\".format(\n                ClassName=self.__class__.__name__, self=self\n            )\n        )\n\n    def __deepcopy__(self, memo):\n        return copy.copy(self)\n\n    def get_value(self, obj, attr, accessor=None, default=missing_):\n        \"\"\"Return the value for a given key from an object.\n\n        :param object obj: The object to get the value from.\n        :param str attr: The attribute/key in `obj` to get the value from.\n        :param callable accessor: A callable used to retrieve the value of `attr` from\n            the object `obj`. Defaults to `marshmallow.utils.get_value`.\n        \"\"\"\n        # NOTE: Use getattr instead of direct attribute access here so that\n        # subclasses aren't required to define `attribute` member\n        attribute = getattr(self, \"attribute\", None)\n        accessor_func = accessor or utils.get_value\n        check_key = attr if attribute is None else attribute\n        return accessor_func(obj, check_key, default)\n\n    def _validate(self, value):\n        \"\"\"Perform validation on ``value``. Raise a :exc:`ValidationError` if validation\n        does not succeed.\n        \"\"\"\n        errors = []\n        kwargs = {}\n        for validator in self.validators:\n            try:\n                r = validator(value)\n                if not isinstance(validator, Validator) and r is False:\n                    raise self.make_error(\"validator_failed\")\n            except ValidationError as err:\n                kwargs.update(err.kwargs)\n                if isinstance(err.messages, dict):\n                    errors.append(err.messages)\n                else:\n                    errors.extend(err.messages)\n        if errors:\n            raise ValidationError(errors, **kwargs)\n\n    def make_error(self, key: str, **kwargs) -> ValidationError:\n        \"\"\"Helper method to make a `ValidationError` with an error message\n        from ``self.error_messages``.\n        \"\"\"\n        try:\n            msg = self.error_messages[key]\n        except KeyError as error:\n            class_name = self.__class__.__name__\n            msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key)\n            raise AssertionError(msg) from error\n        if isinstance(msg, (str, bytes)):\n            msg = msg.format(**kwargs)\n        return ValidationError(msg)\n\n    def fail(self, key: str, **kwargs):\n        \"\"\"Helper method that raises a `ValidationError` with an error message\n        from ``self.error_messages``.\n\n        .. deprecated:: 3.0.0\n            Use `make_error <marshmallow.fields.Field.make_error>` instead.\n        \"\"\"\n        warnings.warn(\n            '`Field.fail` is deprecated. Use `raise self.make_error(\"{}\", ...)` instead.'.format(\n                key\n            ),\n            DeprecationWarning,\n        )\n        raise self.make_error(key=key, **kwargs)\n\n    def _validate_missing(self, value):\n        \"\"\"Validate missing values. Raise a :exc:`ValidationError` if\n        `value` should be considered missing.\n        \"\"\"\n        if value is missing_:\n            if hasattr(self, \"required\") and self.required:\n                raise self.make_error(\"required\")\n        if value is None:\n            if hasattr(self, \"allow_none\") and self.allow_none is not True:\n                raise self.make_error(\"null\")\n\n    def serialize(self, attr, obj, accessor=None, **kwargs):\n        \"\"\"Pulls the value for the given key from the object, applies the\n        field's formatting and returns the result.\n\n        :param str attr: The attribute/key to get from the object.\n        :param str obj: The object to access the attribute/key from.\n        :param callable accessor: Function used to access values from ``obj``.\n        :param dict kwargs: Field-specific keyword arguments.\n        \"\"\"\n        if self._CHECK_ATTRIBUTE:\n            value = self.get_value(obj, attr, accessor=accessor)\n            if value is missing_ and hasattr(self, \"default\"):\n                default = self.default\n                value = default() if callable(default) else default\n            if value is missing_:\n                return value\n        else:\n            value = None\n        return self._serialize(value, attr, obj, **kwargs)\n\n    def deserialize(self, value, attr=None, data=None, **kwargs):\n        \"\"\"Deserialize ``value``.\n\n        :param value: The value to deserialize.\n        :param str attr: The attribute/key in `data` to deserialize.\n        :param dict data: The raw input data passed to `Schema.load`.\n        :param dict kwargs: Field-specific keyword arguments.\n        :raise ValidationError: If an invalid value is passed or if a required value\n            is missing.\n        \"\"\"\n        # Validate required fields, deserialize, then validate\n        # deserialized value\n        self._validate_missing(value)\n        if value is missing_:\n            _miss = self.missing\n            return _miss() if callable(_miss) else _miss\n        if getattr(self, \"allow_none\", False) is True and value is None:\n            return None\n        output = self._deserialize(value, attr, data, **kwargs)\n        self._validate(output)\n        return output\n\n    # Methods for concrete classes to override.\n\n    def _bind_to_schema(self, field_name, schema):\n        \"\"\"Update field with values from its parent schema. Called by\n        :meth:`Schema._bind_field <marshmallow.Schema._bind_field>`.\n\n        :param str field_name: Field name set in schema.\n        :param Schema schema: Parent schema.\n        \"\"\"\n        self.parent = self.parent or schema\n        self.name = self.name or field_name\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        \"\"\"Serializes ``value`` to a basic Python datatype. Noop by default.\n        Concrete :class:`Field` classes should implement this method.\n\n        Example: ::\n\n            class TitleCase(Field):\n                def _serialize(self, value, attr, obj, **kwargs):\n                    if not value:\n                        return ''\n                    return str(value).title()\n\n        :param value: The value to be serialized.\n        :param str attr: The attribute or key on the object to be serialized.\n        :param object obj: The object the value was pulled from.\n        :param dict kwargs: Field-specific keyword arguments.\n        :return: The serialized value\n        \"\"\"\n        return value\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        \"\"\"Deserialize value. Concrete :class:`Field` classes should implement this method.\n\n        :param value: The value to be deserialized.\n        :param str attr: The attribute/key in `data` to be deserialized.\n        :param dict data: The raw input data passed to the `Schema.load`.\n        :param dict kwargs: Field-specific keyword arguments.\n        :raise ValidationError: In case of formatting or validation failure.\n        :return: The deserialized value.\n\n        .. versionchanged:: 2.0.0\n            Added ``attr`` and ``data`` parameters.\n\n        .. versionchanged:: 3.0.0\n            Added ``**kwargs`` to signature.\n        \"\"\"\n        return value\n\n    # Properties\n\n    @property\n    def context(self):\n        \"\"\"The context dictionary for the parent :class:`Schema`.\"\"\"\n        return self.parent.context\n\n    @property\n    def root(self):\n        \"\"\"Reference to the `Schema` that this field belongs to even if it is buried in a\n        container field (e.g. `List`).\n        Return `None` for unbound fields.\n        \"\"\"\n        ret = self\n        while hasattr(ret, \"parent\"):\n            ret = ret.parent\n        return ret if isinstance(ret, SchemaABC) else None\n\n\nclass Raw(Field):\n    \"\"\"Field that applies no formatting or validation.\"\"\"\n\n    pass\n\n\nclass Nested(Field):\n    \"\"\"Allows you to nest a :class:`Schema <marshmallow.Schema>`\n    inside a field.\n\n    Examples: ::\n\n        user = fields.Nested(UserSchema)\n        user2 = fields.Nested('UserSchema')  # Equivalent to above\n        collaborators = fields.Nested(UserSchema, many=True, only=('id',))\n        parent = fields.Nested('self')\n\n    When passing a `Schema <marshmallow.Schema>` instance as the first argument,\n    the instance's ``exclude``, ``only``, and ``many`` attributes will be respected.\n\n    Therefore, when passing the ``exclude``, ``only``, or ``many`` arguments to `fields.Nested`,\n    you should pass a `Schema <marshmallow.Schema>` class (not an instance) as the first argument.\n\n    ::\n\n        # Yes\n        author = fields.Nested(UserSchema, only=('id', 'name'))\n\n        # No\n        author = fields.Nested(UserSchema(), only=('id', 'name'))\n\n    :param Schema nested: The Schema class or class name (string)\n        to nest, or ``\"self\"`` to nest the :class:`Schema` within itself.\n    :param tuple exclude: A list or tuple of fields to exclude.\n    :param only: A list or tuple of fields to marshal. If `None`, all fields are marshalled.\n        This parameter takes precedence over ``exclude``.\n    :param bool many: Whether the field is a collection of objects.\n    :param unknown: Whether to exclude, include, or raise an error for unknown\n        fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n    \"\"\"\n\n    default_error_messages = {\"type\": \"Invalid type.\"}\n\n    def __init__(\n        self, nested, *, default=missing_, exclude=tuple(), only=None, **kwargs\n    ):\n        # Raise error if only or exclude is passed as string, not list of strings\n        if only is not None and not is_collection(only):\n            raise StringNotCollectionError('\"only\" should be a collection of strings.')\n        if exclude is not None and not is_collection(exclude):\n            raise StringNotCollectionError(\n                '\"exclude\" should be a collection of strings.'\n            )\n        self.nested = nested\n        self.only = only\n        self.exclude = exclude\n        self.many = kwargs.get(\"many\", False)\n        self.unknown = kwargs.get(\"unknown\")\n        self._schema = None  # Cached Schema instance\n        super().__init__(default=default, **kwargs)\n\n    @property\n    def schema(self):\n        \"\"\"The nested Schema object.\n\n        .. versionchanged:: 1.0.0\n            Renamed from `serializer` to `schema`.\n        \"\"\"\n        if not self._schema:\n            # Inherit context from parent.\n            context = getattr(self.parent, \"context\", {})\n            if isinstance(self.nested, SchemaABC):\n                self._schema = self.nested\n                self._schema.context.update(context)\n            else:\n                if isinstance(self.nested, type) and issubclass(self.nested, SchemaABC):\n                    schema_class = self.nested\n                elif not isinstance(self.nested, (str, bytes)):\n                    raise ValueError(\n                        \"Nested fields must be passed a \"\n                        \"Schema, not {}.\".format(self.nested.__class__)\n                    )\n                elif self.nested == \"self\":\n                    ret = self\n                    while not isinstance(ret, SchemaABC):\n                        ret = ret.parent\n                    schema_class = ret.__class__\n                else:\n                    schema_class = class_registry.get_class(self.nested)\n                self._schema = schema_class(\n                    many=self.many,\n                    only=self.only,\n                    exclude=self.exclude,\n                    context=context,\n                    load_only=self._nested_normalized_option(\"load_only\"),\n                    dump_only=self._nested_normalized_option(\"dump_only\"),\n                )\n        return self._schema\n\n    def _nested_normalized_option(self, option_name):\n        nested_field = \"%s.\" % self.name\n        return [\n            field.split(nested_field, 1)[1]\n            for field in getattr(self.root, option_name, set())\n            if field.startswith(nested_field)\n        ]\n\n    def _serialize(self, nested_obj, attr, obj, many=False, **kwargs):\n        # Load up the schema first. This allows a RegistryError to be raised\n        # if an invalid schema name was passed\n        schema = self.schema\n        if nested_obj is None:\n            return None\n        return schema.dump(nested_obj, many=self.many or many)\n\n    def _test_collection(self, value, many=False):\n        many = self.many or many\n        if many and not utils.is_collection(value):\n            raise self.make_error(\"type\", input=value, type=value.__class__.__name__)\n\n    def _load(self, value, data, partial=None, many=False):\n        try:\n            valid_data = self.schema.load(\n                value, unknown=self.unknown, partial=partial, many=self.many or many\n            )\n        except ValidationError as error:\n            raise ValidationError(\n                error.messages, valid_data=error.valid_data\n            ) from error\n        return valid_data\n\n    def _deserialize(self, value, attr, data, partial=None, many=False, **kwargs):\n        \"\"\"Same as :meth:`Field._deserialize` with additional ``partial`` argument.\n\n        :param bool|tuple partial: For nested schemas, the ``partial``\n            parameter passed to `Schema.load`.\n\n        .. versionchanged:: 3.0.0\n            Add ``partial`` parameter.\n        \"\"\"\n        self._test_collection(value, many=many)\n        return self._load(value, data, partial=partial, many=many)\n\n\nclass Pluck(Nested):\n    \"\"\"Allows you to replace nested data with one of the data's fields.\n\n    Example: ::\n\n        from marshmallow import Schema, fields\n\n        class ArtistSchema(Schema):\n            id = fields.Int()\n            name = fields.Str()\n\n        class AlbumSchema(Schema):\n            artist = fields.Pluck(ArtistSchema, 'id')\n\n\n        in_data = {'artist': 42}\n        loaded = AlbumSchema().load(in_data) # => {'artist': {'id': 42}}\n        dumped = AlbumSchema().dump(loaded)  # => {'artist': 42}\n\n    :param Schema nested: The Schema class or class name (string)\n        to nest, or ``\"self\"`` to nest the :class:`Schema` within itself.\n    :param str field_name: The key to pluck a value from.\n    :param kwargs: The same keyword arguments that :class:`Nested` receives.\n    \"\"\"\n\n    def __init__(self, nested, field_name, **kwargs):\n        super().__init__(nested, only=(field_name,), **kwargs)\n        self.field_name = field_name\n\n    @property\n    def _field_data_key(self):\n        only_field = self.schema.fields[self.field_name]\n        return only_field.data_key or self.field_name\n\n    def _serialize(self, nested_obj, attr, obj, **kwargs):\n        ret = super()._serialize(nested_obj, attr, obj, **kwargs)\n        if ret is None:\n            return None\n        if self.many:\n            return utils.pluck(ret, key=self._field_data_key)\n        return ret[self._field_data_key]\n\n    def _deserialize(self, value, attr, data, partial=None, **kwargs):\n        self._test_collection(value)\n        if self.many:\n            value = [{self._field_data_key: v} for v in value]\n        else:\n            value = {self._field_data_key: value}\n        return self._load(value, data, partial=partial)\n\n\nclass List(Field):\n    \"\"\"A list field, composed with another `Field` class or\n    instance.\n\n    Example: ::\n\n        numbers = fields.List(fields.Float())\n\n    :param Field cls_or_instance: A field class or instance.\n    :param bool default: Default value for serialization.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n\n    .. versionchanged:: 2.0.0\n        The ``allow_none`` parameter now applies to deserialization and\n        has the same semantics as the other fields.\n\n    .. versionchanged:: 3.0.0rc9\n        Does not serialize scalar values to single-item lists.\n    \"\"\"\n\n    default_error_messages = {\"invalid\": \"Not a valid list.\"}\n\n    def __init__(self, cls_or_instance, **kwargs):\n        super().__init__(**kwargs)\n        try:\n            self.inner = resolve_field_instance(cls_or_instance)\n        except FieldInstanceResolutionError as error:\n            raise ValueError(\n                \"The list elements must be a subclass or instance of \"\n                \"marshmallow.base.FieldABC.\"\n            ) from error\n        if isinstance(self.inner, Nested):\n            self.only = self.inner.only\n            self.exclude = self.inner.exclude\n\n    def _bind_to_schema(self, field_name, schema):\n        super()._bind_to_schema(field_name, schema)\n        self.inner = copy.deepcopy(self.inner)\n        self.inner._bind_to_schema(field_name, self)\n        if isinstance(self.inner, Nested):\n            self.inner.only = self.only\n            self.inner.exclude = self.exclude\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n        # Optimize dumping a list of Nested objects by calling dump(many=True)\n        if isinstance(self.inner, Nested) and not self.inner.many:\n            return self.inner._serialize(value, attr, obj, many=True, **kwargs)\n        return [self.inner._serialize(each, attr, obj, **kwargs) for each in value]\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if not utils.is_collection(value):\n            raise self.make_error(\"invalid\")\n        # Optimize loading a list of Nested objects by calling load(many=True)\n        if isinstance(self.inner, Nested) and not self.inner.many:\n            return self.inner.deserialize(value, many=True, **kwargs)\n\n        result = []\n        errors = {}\n        for idx, each in enumerate(value):\n            try:\n                result.append(self.inner.deserialize(each, **kwargs))\n            except ValidationError as error:\n                if error.valid_data is not None:\n                    result.append(error.valid_data)\n                errors.update({idx: error.messages})\n        if errors:\n            raise ValidationError(errors, valid_data=result)\n        return result\n\n\nclass Tuple(Field):\n    \"\"\"A tuple field, composed of a fixed number of other `Field` classes or\n    instances\n\n    Example: ::\n\n        row = Tuple((fields.String(), fields.Integer(), fields.Float()))\n\n    .. note::\n        Because of the structured nature of `collections.namedtuple` and\n        `typing.NamedTuple`, using a Schema within a Nested field for them is\n        more appropriate than using a `Tuple` field.\n\n    :param Iterable[Field] tuple_fields: An iterable of field classes or\n        instances.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n\n    .. versionadded:: 3.0.0rc4\n    \"\"\"\n\n    default_error_messages = {\"invalid\": \"Not a valid tuple.\"}\n\n    def __init__(self, tuple_fields, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        if not utils.is_collection(tuple_fields):\n            raise ValueError(\n                \"tuple_fields must be an iterable of Field classes or \" \"instances.\"\n            )\n\n        try:\n            self.tuple_fields = [\n                resolve_field_instance(cls_or_instance)\n                for cls_or_instance in tuple_fields\n            ]\n        except FieldInstanceResolutionError as error:\n            raise ValueError(\n                'Elements of \"tuple_fields\" must be subclasses or '\n                \"instances of marshmallow.base.FieldABC.\"\n            ) from error\n\n        self.validate_length = Length(equal=len(self.tuple_fields))\n\n    def _bind_to_schema(self, field_name, schema):\n        super()._bind_to_schema(field_name, schema)\n        new_tuple_fields = []\n        for field in self.tuple_fields:\n            field = copy.deepcopy(field)\n            field._bind_to_schema(field_name, self)\n            new_tuple_fields.append(field)\n\n        self.tuple_fields = new_tuple_fields\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n\n        return tuple(\n            field._serialize(each, attr, obj, **kwargs)\n            for field, each in zip(self.tuple_fields, value)\n        )\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if not utils.is_collection(value):\n            raise self.make_error(\"invalid\")\n\n        self.validate_length(value)\n\n        result = []\n        errors = {}\n\n        for idx, (field, each) in enumerate(zip(self.tuple_fields, value)):\n            try:\n                result.append(field.deserialize(each, **kwargs))\n            except ValidationError as error:\n                if error.valid_data is not None:\n                    result.append(error.valid_data)\n                errors.update({idx: error.messages})\n        if errors:\n            raise ValidationError(errors, valid_data=result)\n\n        return tuple(result)\n\n\nclass String(Field):\n    \"\"\"A string field.\n\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n    \"\"\"\n\n    default_error_messages = {\n        \"invalid\": \"Not a valid string.\",\n        \"invalid_utf8\": \"Not a valid utf-8 string.\",\n    }\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n        return utils.ensure_text_type(value)\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if not isinstance(value, (str, bytes)):\n            raise self.make_error(\"invalid\")\n        try:\n            return utils.ensure_text_type(value)\n        except UnicodeDecodeError as error:\n            raise self.make_error(\"invalid_utf8\") from error\n\n\nclass UUID(String):\n    \"\"\"A UUID field.\"\"\"\n\n    default_error_messages = {\"invalid_uuid\": \"Not a valid UUID.\"}\n\n    def _validated(self, value):\n        \"\"\"Format the value or raise a :exc:`ValidationError` if an error occurs.\"\"\"\n        if value is None:\n            return None\n        if isinstance(value, uuid.UUID):\n            return value\n        try:\n            if isinstance(value, bytes) and len(value) == 16:\n                return uuid.UUID(bytes=value)\n            else:\n                return uuid.UUID(value)\n        except (ValueError, AttributeError, TypeError) as error:\n            raise self.make_error(\"invalid_uuid\") from error\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        val = str(value) if value is not None else None\n        return super()._serialize(val, attr, obj, **kwargs)\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        return self._validated(value)\n\n\nclass Number(Field):\n    \"\"\"Base class for number fields.\n\n    :param bool as_string: If True, format the serialized value as a string.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n    \"\"\"\n\n    num_type = float\n    default_error_messages = {\n        \"invalid\": \"Not a valid number.\",\n        \"too_large\": \"Number too large.\",\n    }\n\n    def __init__(self, *, as_string=False, **kwargs):\n        self.as_string = as_string\n        super().__init__(**kwargs)\n\n    def _format_num(self, value):\n        \"\"\"Return the number value for value, given this field's `num_type`.\"\"\"\n        return self.num_type(value)\n\n    def _validated(self, value):\n        \"\"\"Format the value or raise a :exc:`ValidationError` if an error occurs.\"\"\"\n        if value is None:\n            return None\n        # (value is True or value is False) is ~5x faster than isinstance(value, bool)\n        if value is True or value is False:\n            raise self.make_error(\"invalid\", input=value)\n        try:\n            return self._format_num(value)\n        except (TypeError, ValueError) as error:\n            raise self.make_error(\"invalid\", input=value) from error\n        except OverflowError as error:\n            raise self.make_error(\"too_large\", input=value) from error\n\n    def _to_string(self, value):\n        return str(value)\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        \"\"\"Return a string if `self.as_string=True`, otherwise return this field's `num_type`.\"\"\"\n        if value is None:\n            return None\n        ret = self._format_num(value)\n        return self._to_string(ret) if self.as_string else ret\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        return self._validated(value)\n\n\nclass Integer(Number):\n    \"\"\"An integer field.\n\n    :param kwargs: The same keyword arguments that :class:`Number` receives.\n    \"\"\"\n\n    num_type = int\n    default_error_messages = {\"invalid\": \"Not a valid integer.\"}\n\n    def __init__(self, *, strict=False, **kwargs):\n        self.strict = strict\n        super().__init__(**kwargs)\n\n    # override Number\n    def _validated(self, value):\n        if self.strict:\n            if isinstance(value, numbers.Number) and isinstance(\n                value, numbers.Integral\n            ):\n                return super()._validated(value)\n            raise self.make_error(\"invalid\", input=value)\n        return super()._validated(value)\n\n\nclass Float(Number):\n    \"\"\"A double as an IEEE-754 double precision string.\n\n    :param bool allow_nan: If `True`, `NaN`, `Infinity` and `-Infinity` are allowed,\n        even though they are illegal according to the JSON specification.\n    :param bool as_string: If True, format the value as a string.\n    :param kwargs: The same keyword arguments that :class:`Number` receives.\n    \"\"\"\n\n    num_type = float\n    default_error_messages = {\n        \"special\": \"Special numeric values (nan or infinity) are not permitted.\"\n    }\n\n    def __init__(self, *, allow_nan=False, as_string=False, **kwargs):\n        self.allow_nan = allow_nan\n        super().__init__(as_string=as_string, **kwargs)\n\n    def _validated(self, value):\n        num = super()._validated(value)\n        if self.allow_nan is False:\n            if math.isnan(num) or num == float(\"inf\") or num == float(\"-inf\"):\n                raise self.make_error(\"special\")\n        return num\n\n\nclass Decimal(Number):\n    \"\"\"A field that (de)serializes to the Python ``decimal.Decimal`` type.\n    It's safe to use when dealing with money values, percentages, ratios\n    or other numbers where precision is critical.\n\n    .. warning::\n\n        This field serializes to a `decimal.Decimal` object by default. If you need\n        to render your data as JSON, keep in mind that the `json` module from the\n        standard library does not encode `decimal.Decimal`. Therefore, you must use\n        a JSON library that can handle decimals, such as `simplejson`, or serialize\n        to a string by passing ``as_string=True``.\n\n    .. warning::\n\n        If a JSON `float` value is passed to this field for deserialization it will\n        first be cast to its corresponding `string` value before being deserialized\n        to a `decimal.Decimal` object. The default `__str__` implementation of the\n        built-in Python `float` type may apply a destructive transformation upon\n        its input data and therefore cannot be relied upon to preserve precision.\n        To avoid this, you can instead pass a JSON `string` to be deserialized\n        directly.\n\n    :param int places: How many decimal places to quantize the value. If `None`, does\n        not quantize the value.\n    :param rounding: How to round the value during quantize, for example\n        `decimal.ROUND_UP`. If None, uses the rounding value from\n        the current thread's context.\n    :param bool allow_nan: If `True`, `NaN`, `Infinity` and `-Infinity` are allowed,\n        even though they are illegal according to the JSON specification.\n    :param bool as_string: If True, serialize to a string instead of a Python\n        `decimal.Decimal` type.\n    :param kwargs: The same keyword arguments that :class:`Number` receives.\n\n    .. versionadded:: 1.2.0\n    \"\"\"\n\n    num_type = decimal.Decimal\n\n    default_error_messages = {\n        \"special\": \"Special numeric values (nan or infinity) are not permitted.\"\n    }\n\n    def __init__(\n        self, places=None, rounding=None, *, allow_nan=False, as_string=False, **kwargs\n    ):\n        self.places = (\n            decimal.Decimal((0, (1,), -places)) if places is not None else None\n        )\n        self.rounding = rounding\n        self.allow_nan = allow_nan\n        super().__init__(as_string=as_string, **kwargs)\n\n    # override Number\n    def _format_num(self, value):\n        num = decimal.Decimal(str(value))\n        if self.allow_nan:\n            if num.is_nan():\n                return decimal.Decimal(\"NaN\")  # avoid sNaN, -sNaN and -NaN\n        if self.places is not None and num.is_finite():\n            num = num.quantize(self.places, rounding=self.rounding)\n        return num\n\n    # override Number\n    def _validated(self, value):\n        try:\n            num = super()._validated(value)\n        except decimal.InvalidOperation as error:\n            raise self.make_error(\"invalid\") from error\n        if not self.allow_nan and (num.is_nan() or num.is_infinite()):\n            raise self.make_error(\"special\")\n        return num\n\n    # override Number\n    def _to_string(self, value):\n        return format(value, \"f\")\n\n\nclass Boolean(Field):\n    \"\"\"A boolean field.\n\n    :param set truthy: Values that will (de)serialize to `True`. If an empty\n        set, any non-falsy value will deserialize to `True`. If `None`,\n        `marshmallow.fields.Boolean.truthy` will be used.\n    :param set falsy: Values that will (de)serialize to `False`. If `None`,\n        `marshmallow.fields.Boolean.falsy` will be used.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n    \"\"\"\n\n    #: Default truthy values.\n    truthy = {\n        \"t\",\n        \"T\",\n        \"true\",\n        \"True\",\n        \"TRUE\",\n        \"on\",\n        \"On\",\n        \"ON\",\n        \"y\",\n        \"Y\",\n        \"yes\",\n        \"Yes\",\n        \"YES\",\n        \"1\",\n        1,\n        True,\n    }\n    #: Default falsy values.\n    falsy = {\n        \"f\",\n        \"F\",\n        \"false\",\n        \"False\",\n        \"FALSE\",\n        \"off\",\n        \"Off\",\n        \"OFF\",\n        \"n\",\n        \"N\",\n        \"no\",\n        \"No\",\n        \"NO\",\n        \"0\",\n        0,\n        0.0,\n        False,\n    }\n\n    default_error_messages = {\"invalid\": \"Not a valid boolean.\"}\n\n    def __init__(self, *, truthy=None, falsy=None, **kwargs):\n        super().__init__(**kwargs)\n\n        if truthy is not None:\n            self.truthy = set(truthy)\n        if falsy is not None:\n            self.falsy = set(falsy)\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n        elif value in self.truthy:\n            return True\n        elif value in self.falsy:\n            return False\n\n        return bool(value)\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if not self.truthy:\n            return bool(value)\n        else:\n            try:\n                if value in self.truthy:\n                    return True\n                elif value in self.falsy:\n                    return False\n            except TypeError as error:\n                raise self.make_error(\"invalid\", input=value) from error\n        raise self.make_error(\"invalid\", input=value)\n\n\nclass DateTime(Field):\n    \"\"\"A formatted datetime string.\n\n    Example: ``'2014-12-22T03:12:58.019077+00:00'``\n\n    :param str format: Either ``\"rfc\"`` (for RFC822), ``\"iso\"`` (for ISO8601),\n        or a date format string. If `None`, defaults to \"iso\".\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n\n    .. versionchanged:: 3.0.0rc9\n        Does not modify timezone information on (de)serialization.\n    \"\"\"\n\n    SERIALIZATION_FUNCS = {\n        \"iso\": utils.isoformat,\n        \"iso8601\": utils.isoformat,\n        \"rfc\": utils.rfcformat,\n        \"rfc822\": utils.rfcformat,\n    }\n\n    DESERIALIZATION_FUNCS = {\n        \"iso\": utils.from_iso_datetime,\n        \"iso8601\": utils.from_iso_datetime,\n        \"rfc\": utils.from_rfc,\n        \"rfc822\": utils.from_rfc,\n    }\n\n    DEFAULT_FORMAT = \"iso\"\n\n    OBJ_TYPE = \"datetime\"\n\n    SCHEMA_OPTS_VAR_NAME = \"datetimeformat\"\n\n    default_error_messages = {\n        \"invalid\": \"Not a valid {obj_type}.\",\n        \"invalid_awareness\": \"Not a valid {awareness} {obj_type}.\",\n        \"format\": '\"{input}\" cannot be formatted as a {obj_type}.',\n    }\n\n    def __init__(self, format=None, **kwargs):\n        super().__init__(**kwargs)\n        # Allow this to be None. It may be set later in the ``_serialize``\n        # or ``_deserialize`` methods. This allows a Schema to dynamically set the\n        # format, e.g. from a Meta option\n        self.format = format\n\n    def _bind_to_schema(self, field_name, schema):\n        super()._bind_to_schema(field_name, schema)\n        self.format = (\n            self.format\n            or getattr(self.root.opts, self.SCHEMA_OPTS_VAR_NAME)\n            or self.DEFAULT_FORMAT\n        )\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n        data_format = self.format or self.DEFAULT_FORMAT\n        format_func = self.SERIALIZATION_FUNCS.get(data_format)\n        if format_func:\n            return format_func(value)\n        else:\n            return value.strftime(data_format)\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if not value:  # Falsy values, e.g. '', None, [] are not valid\n            raise self.make_error(\"invalid\", input=value, obj_type=self.OBJ_TYPE)\n        data_format = self.format or self.DEFAULT_FORMAT\n        func = self.DESERIALIZATION_FUNCS.get(data_format)\n        if func:\n            try:\n                return func(value)\n            except (TypeError, AttributeError, ValueError) as error:\n                raise self.make_error(\n                    \"invalid\", input=value, obj_type=self.OBJ_TYPE\n                ) from error\n        else:\n            try:\n                return self._make_object_from_format(value, data_format)\n            except (TypeError, AttributeError, ValueError) as error:\n                raise self.make_error(\n                    \"invalid\", input=value, obj_type=self.OBJ_TYPE\n                ) from error\n\n    @staticmethod\n    def _make_object_from_format(value, data_format):\n        return dt.datetime.strptime(value, data_format)\n\n\nclass NaiveDateTime(DateTime):\n    \"\"\"A formatted naive datetime string.\n\n    :param str format: See :class:`DateTime`.\n    :param timezone timezone: Used on deserialization. If `None`,\n        aware datetimes are rejected. If not `None`, aware datetimes are\n        converted to this timezone before their timezone information is\n        removed.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n\n    .. versionadded:: 3.0.0rc9\n    \"\"\"\n\n    AWARENESS = \"naive\"\n\n    def __init__(self, format=None, *, timezone=None, **kwargs):\n        super().__init__(format=format, **kwargs)\n        self.timezone = timezone\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        ret = super()._deserialize(value, attr, data, **kwargs)\n        if is_aware(ret):\n            if self.timezone is None:\n                raise self.make_error(\n                    \"invalid_awareness\",\n                    awareness=self.AWARENESS,\n                    obj_type=self.OBJ_TYPE,\n                )\n            ret = ret.astimezone(self.timezone).replace(tzinfo=None)\n        return ret\n\n\nclass AwareDateTime(DateTime):\n    \"\"\"A formatted aware datetime string.\n\n    :param str format: See :class:`DateTime`.\n    :param timezone default_timezone: Used on deserialization. If `None`, naive\n        datetimes are rejected. If not `None`, naive datetimes are set this\n        timezone.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n\n    .. versionadded:: 3.0.0rc9\n    \"\"\"\n\n    AWARENESS = \"aware\"\n\n    def __init__(self, format=None, *, default_timezone=None, **kwargs):\n        super().__init__(format=format, **kwargs)\n        self.default_timezone = default_timezone\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        ret = super()._deserialize(value, attr, data, **kwargs)\n        if not is_aware(ret):\n            if self.default_timezone is None:\n                raise self.make_error(\n                    \"invalid_awareness\",\n                    awareness=self.AWARENESS,\n                    obj_type=self.OBJ_TYPE,\n                )\n            ret = ret.replace(tzinfo=self.default_timezone)\n        return ret\n\n\nclass Time(Field):\n    \"\"\"ISO8601-formatted time string.\n\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n    \"\"\"\n\n    default_error_messages = {\n        \"invalid\": \"Not a valid time.\",\n        \"format\": '\"{input}\" cannot be formatted as a time.',\n    }\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n        ret = value.isoformat()\n        if value.microsecond:\n            return ret[:15]\n        return ret\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        \"\"\"Deserialize an ISO8601-formatted time to a :class:`datetime.time` object.\"\"\"\n        if not value:  # falsy values are invalid\n            raise self.make_error(\"invalid\")\n        try:\n            return utils.from_iso_time(value)\n        except (AttributeError, TypeError, ValueError) as error:\n            raise self.make_error(\"invalid\") from error\n\n\nclass Date(DateTime):\n    \"\"\"ISO8601-formatted date string.\n\n    :param format: Either ``\"iso\"`` (for ISO8601) or a date format string.\n        If `None`, defaults to \"iso\".\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n    \"\"\"\n\n    default_error_messages = {\n        \"invalid\": \"Not a valid date.\",\n        \"format\": '\"{input}\" cannot be formatted as a date.',\n    }\n\n    SERIALIZATION_FUNCS = {\"iso\": utils.to_iso_date, \"iso8601\": utils.to_iso_date}\n\n    DESERIALIZATION_FUNCS = {\"iso\": utils.from_iso_date, \"iso8601\": utils.from_iso_date}\n\n    DEFAULT_FORMAT = \"iso\"\n\n    OBJ_TYPE = \"date\"\n\n    SCHEMA_OPTS_VAR_NAME = \"dateformat\"\n\n    @staticmethod\n    def _make_object_from_format(value, data_format):\n        return dt.datetime.strptime(value, data_format).date()\n\n\nclass TimeDelta(Field):\n    \"\"\"A field that (de)serializes a :class:`datetime.timedelta` object to an\n    integer and vice versa. The integer can represent the number of days,\n    seconds or microseconds.\n\n    :param str precision: Influences how the integer is interpreted during\n        (de)serialization. Must be 'days', 'seconds', 'microseconds',\n        'milliseconds', 'minutes', 'hours' or 'weeks'.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n\n    .. versionchanged:: 2.0.0\n        Always serializes to an integer value to avoid rounding errors.\n        Add `precision` parameter.\n    \"\"\"\n\n    DAYS = \"days\"\n    SECONDS = \"seconds\"\n    MICROSECONDS = \"microseconds\"\n    MILLISECONDS = \"milliseconds\"\n    MINUTES = \"minutes\"\n    HOURS = \"hours\"\n    WEEKS = \"weeks\"\n\n    default_error_messages = {\n        \"invalid\": \"Not a valid period of time.\",\n        \"format\": \"{input!r} cannot be formatted as a timedelta.\",\n    }\n\n    def __init__(self, precision=SECONDS, **kwargs):\n        precision = precision.lower()\n        units = (\n            self.DAYS,\n            self.SECONDS,\n            self.MICROSECONDS,\n            self.MILLISECONDS,\n            self.MINUTES,\n            self.HOURS,\n            self.WEEKS,\n        )\n\n        if precision not in units:\n            msg = 'The precision must be {} or \"{}\".'.format(\n                \", \".join(['\"{}\"'.format(each) for each in units[:-1]]), units[-1]\n            )\n            raise ValueError(msg)\n\n        self.precision = precision\n        super().__init__(**kwargs)\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n        base_unit = dt.timedelta(**{self.precision: 1})\n        return int(value.total_seconds() / base_unit.total_seconds())\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        try:\n            value = int(value)\n        except (TypeError, ValueError) as error:\n            raise self.make_error(\"invalid\") from error\n\n        kwargs = {self.precision: value}\n\n        try:\n            return dt.timedelta(**kwargs)\n        except OverflowError as error:\n            raise self.make_error(\"invalid\") from error\n\n\nclass Mapping(Field):\n    \"\"\"An abstract class for objects with key-value pairs.\n\n    :param Field keys: A field class or instance for dict keys.\n    :param Field values: A field class or instance for dict values.\n    :param kwargs: The same keyword arguments that :class:`Field` receives.\n\n    .. note::\n        When the structure of nested data is not known, you may omit the\n        `keys` and `values` arguments to prevent content validation.\n\n    .. versionadded:: 3.0.0rc4\n    \"\"\"\n\n    mapping_type = dict\n    default_error_messages = {\"invalid\": \"Not a valid mapping type.\"}\n\n    def __init__(self, keys=None, values=None, **kwargs):\n        super().__init__(**kwargs)\n        if keys is None:\n            self.key_field = None\n        else:\n            try:\n                self.key_field = resolve_field_instance(keys)\n            except FieldInstanceResolutionError as error:\n                raise ValueError(\n                    '\"keys\" must be a subclass or instance of '\n                    \"marshmallow.base.FieldABC.\"\n                ) from error\n\n        if values is None:\n            self.value_field = None\n        else:\n            try:\n                self.value_field = resolve_field_instance(values)\n            except FieldInstanceResolutionError as error:\n                raise ValueError(\n                    '\"values\" must be a subclass or instance of '\n                    \"marshmallow.base.FieldABC.\"\n                ) from error\n            if isinstance(self.value_field, Nested):\n                self.only = self.value_field.only\n                self.exclude = self.value_field.exclude\n\n    def _bind_to_schema(self, field_name, schema):\n        super()._bind_to_schema(field_name, schema)\n        if self.value_field:\n            self.value_field = copy.deepcopy(self.value_field)\n            self.value_field._bind_to_schema(field_name, self)\n        if isinstance(self.value_field, Nested):\n            self.value_field.only = self.only\n            self.value_field.exclude = self.exclude\n        if self.key_field:\n            self.key_field = copy.deepcopy(self.key_field)\n            self.key_field._bind_to_schema(field_name, self)\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if value is None:\n            return None\n        if not self.value_field and not self.key_field:\n            return value\n\n        #  Serialize keys\n        if self.key_field is None:\n            keys = {k: k for k in value.keys()}\n        else:\n            keys = {\n                k: self.key_field._serialize(k, None, None, **kwargs)\n                for k in value.keys()\n            }\n\n        #  Serialize values\n        result = self.mapping_type()\n        if self.value_field is None:\n            for k, v in value.items():\n                if k in keys:\n                    result[keys[k]] = v\n        else:\n            for k, v in value.items():\n                result[keys[k]] = self.value_field._serialize(v, None, None, **kwargs)\n\n        return result\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if not isinstance(value, _Mapping):\n            raise self.make_error(\"invalid\")\n        if not self.value_field and not self.key_field:\n            return value\n\n        errors = collections.defaultdict(dict)\n\n        #  Deserialize keys\n        if self.key_field is None:\n            keys = {k: k for k in value.keys()}\n        else:\n            keys = {}\n            for key in value.keys():\n                try:\n                    keys[key] = self.key_field.deserialize(key, **kwargs)\n                except ValidationError as error:\n                    errors[key][\"key\"] = error.messages\n\n        #  Deserialize values\n        result = self.mapping_type()\n        if self.value_field is None:\n            for k, v in value.items():\n                if k in keys:\n                    result[keys[k]] = v\n        else:\n            for key, val in value.items():\n                try:\n                    deser_val = self.value_field.deserialize(val, **kwargs)\n                except ValidationError as error:\n                    errors[key][\"value\"] = error.messages\n                    if error.valid_data is not None and key in keys:\n                        result[keys[key]] = error.valid_data\n                else:\n                    if key in keys:\n                        result[keys[key]] = deser_val\n\n        if errors:\n            raise ValidationError(errors, valid_data=result)\n\n        return result\n\n\nclass Dict(Mapping):\n    \"\"\"A dict field. Supports dicts and dict-like objects. Extends\n    Mapping with dict as the mapping_type.\n\n    Example: ::\n\n        numbers = fields.Dict(keys=fields.Str(), values=fields.Float())\n\n    :param kwargs: The same keyword arguments that :class:`Mapping` receives.\n\n    .. versionadded:: 2.1.0\n    \"\"\"\n\n    mapping_type = dict\n\n\nclass Url(String):\n    \"\"\"A validated URL field. Validation occurs during both serialization and\n    deserialization.\n\n    :param default: Default value for the field if the attribute is not set.\n    :param str attribute: The name of the attribute to get the value from. If\n        `None`, assumes the attribute has the same name as the field.\n    :param bool relative: Whether to allow relative URLs.\n    :param bool require_tld: Whether to reject non-FQDN hostnames.\n    :param kwargs: The same keyword arguments that :class:`String` receives.\n    \"\"\"\n\n    default_error_messages = {\"invalid\": \"Not a valid URL.\"}\n\n    def __init__(self, *, relative=False, schemes=None, require_tld=True, **kwargs):\n        super().__init__(**kwargs)\n\n        self.relative = relative\n        self.require_tld = require_tld\n        # Insert validation into self.validators so that multiple errors can be\n        # stored.\n        self.validators.insert(\n            0,\n            validate.URL(\n                relative=self.relative,\n                schemes=schemes,\n                require_tld=self.require_tld,\n                error=self.error_messages[\"invalid\"],\n            ),\n        )\n\n\nclass Email(String):\n    \"\"\"A validated email field. Validation occurs during both serialization and\n    deserialization.\n\n    :param args: The same positional arguments that :class:`String` receives.\n    :param kwargs: The same keyword arguments that :class:`String` receives.\n    \"\"\"\n\n    default_error_messages = {\"invalid\": \"Not a valid email address.\"}\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        # Insert validation into self.validators so that multiple errors can be\n        # stored.\n        self.validators.insert(0, validate.Email(error=self.error_messages[\"invalid\"]))\n\n\nclass Method(Field):\n    \"\"\"A field that takes the value returned by a `Schema` method.\n\n    :param str serialize: The name of the Schema method from which\n        to retrieve the value. The method must take an argument ``obj``\n        (in addition to self) that is the object to be serialized.\n    :param str deserialize: Optional name of the Schema method for deserializing\n        a value The method must take a single argument ``value``, which is the\n        value to deserialize.\n\n    .. versionchanged:: 2.0.0\n        Removed optional ``context`` parameter on methods. Use ``self.context`` instead.\n\n    .. versionchanged:: 2.3.0\n        Deprecated ``method_name`` parameter in favor of ``serialize`` and allow\n        ``serialize`` to not be passed at all.\n\n    .. versionchanged:: 3.0.0\n        Removed ``method_name`` parameter.\n    \"\"\"\n\n    _CHECK_ATTRIBUTE = False\n\n    def __init__(self, serialize=None, deserialize=None, **kwargs):\n        # Set dump_only and load_only based on arguments\n        kwargs[\"dump_only\"] = bool(serialize) and not bool(deserialize)\n        kwargs[\"load_only\"] = bool(deserialize) and not bool(serialize)\n        super().__init__(**kwargs)\n        self.serialize_method_name = serialize\n        self.deserialize_method_name = deserialize\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        if not self.serialize_method_name:\n            return missing_\n\n        method = utils.callable_or_raise(\n            getattr(self.parent, self.serialize_method_name, None)\n        )\n        return method(obj)\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if self.deserialize_method_name:\n            method = utils.callable_or_raise(\n                getattr(self.parent, self.deserialize_method_name, None)\n            )\n            return method(value)\n        return value\n\n\nclass Function(Field):\n    \"\"\"A field that takes the value returned by a function.\n\n    :param callable serialize: A callable from which to retrieve the value.\n        The function must take a single argument ``obj`` which is the object\n        to be serialized. It can also optionally take a ``context`` argument,\n        which is a dictionary of context variables passed to the serializer.\n        If no callable is provided then the ```load_only``` flag will be set\n        to True.\n    :param callable deserialize: A callable from which to retrieve the value.\n        The function must take a single argument ``value`` which is the value\n        to be deserialized. It can also optionally take a ``context`` argument,\n        which is a dictionary of context variables passed to the deserializer.\n        If no callable is provided then ```value``` will be passed through\n        unchanged.\n\n    .. versionchanged:: 2.3.0\n        Deprecated ``func`` parameter in favor of ``serialize``.\n\n    .. versionchanged:: 3.0.0a1\n        Removed ``func`` parameter.\n    \"\"\"\n\n    _CHECK_ATTRIBUTE = False\n\n    def __init__(self, serialize=None, deserialize=None, **kwargs):\n        # Set dump_only and load_only based on arguments\n        kwargs[\"dump_only\"] = bool(serialize) and not bool(deserialize)\n        kwargs[\"load_only\"] = bool(deserialize) and not bool(serialize)\n        super().__init__(**kwargs)\n        self.serialize_func = serialize and utils.callable_or_raise(serialize)\n        self.deserialize_func = deserialize and utils.callable_or_raise(deserialize)\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        return self._call_or_raise(self.serialize_func, obj, attr)\n\n    def _deserialize(self, value, attr, data, **kwargs):\n        if self.deserialize_func:\n            return self._call_or_raise(self.deserialize_func, value, attr)\n        return value\n\n    def _call_or_raise(self, func, value, attr):\n        if len(utils.get_func_args(func)) > 1:\n            if self.parent.context is None:\n                msg = \"No context available for Function field {!r}\".format(attr)\n                raise ValidationError(msg)\n            return func(value, self.parent.context)\n        else:\n            return func(value)\n\n\nclass Constant(Field):\n    \"\"\"A field that (de)serializes to a preset constant.  If you only want the\n    constant added for serialization or deserialization, you should use\n    ``dump_only=True`` or ``load_only=True`` respectively.\n\n    :param constant: The constant to return for the field attribute.\n\n    .. versionadded:: 2.0.0\n    \"\"\"\n\n    _CHECK_ATTRIBUTE = False\n\n    def __init__(self, constant, **kwargs):\n        super().__init__(**kwargs)\n        self.constant = constant\n        self.missing = constant\n        self.default = constant\n\n    def _serialize(self, value, *args, **kwargs):\n        return self.constant\n\n    def _deserialize(self, value, *args, **kwargs):\n        return self.constant\n\n\nclass Inferred(Field):\n    \"\"\"A field that infers how to serialize, based on the value type.\n\n    .. warning::\n\n        This class is treated as private API.\n        Users should not need to use this class directly.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        # We memoize the fields to avoid creating and binding new fields\n        # every time on serialization.\n        self._field_cache = {}\n\n    def _serialize(self, value, attr, obj, **kwargs):\n        field_cls = self.root.TYPE_MAPPING.get(type(value))\n        if field_cls is None:\n            field = super()\n        else:\n            field = self._field_cache.get(field_cls)\n            if field is None:\n                field = field_cls()\n                field._bind_to_schema(self.name, self.parent)\n                self._field_cache[field_cls] = field\n        return field._serialize(value, attr, obj, **kwargs)\n\n\n# Aliases\nURL = Url\nStr = String\nBool = Boolean\nInt = Integer\n","header":{"file":{"path":"src/marshmallow/fields.py"},"misc_line":null},"index_line":null,"is_binary_file":false,"binary_line":null,"minus_file":{"path":"a/src/marshmallow/fields.py"},"plus_file":{"path":"b/src/marshmallow/fields.py"},"hunks":[{"descriptor":{"old_range":{"start":1114,"length":7},"new_range":{"start":1114,"length":7},"section":"def _bind_to_schema(self, field_name, schema):"},"line_group":{"all_lines":[{"content":"        super()._bind_to_schema(field_name, schema)","type":"context"},{"content":"        self.format = (","type":"context"},{"content":"            self.format","type":"context"},{"content":"            or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME)","type":"deleted"},{"content":"            or getattr(self.root.opts, self.SCHEMA_OPTS_VAR_NAME)","type":"added"},{"content":"            or self.DEFAULT_FORMAT","type":"context"},{"content":"        )","type":"context"},{"content":"","type":"context"},{"content":"","type":"context"}]},"modified_entities":[],"added_entities":[],"deleted_entities":[]}]}],"old_commit_hash":"b40a0f4e33823e6d0f341f7e8684e359a99060d1","new_commit_hash":"a180a25e83203b5f8e55dc685d132a30158272e9","commit_message":"Update changelog","commit_date":"2019-08-21T13:50:03-04:00","metadata":{}}