prompt: 
  We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  [version 2.20.0] TypeError: 'NoneType' object is not subscriptable
  After update from version 2.19.5 to 2.20.0 I got error for code like:
  
  ```python
  from marshmallow import Schema, fields, validates
  
  
  class Bar(Schema):
      value = fields.String()
  
      @validates('value')  # <- issue here
      def validate_value(self, value):
          pass
  
  
  class Foo(Schema):
      bar = fields.Nested(Bar)
  
  
  sch = Foo()
  
  sch.validate({
      'bar': 'invalid',
  })
  ```
  
  ```
  Traceback (most recent call last):
    File "/_/bug_mschema.py", line 19, in <module>
      'bar': 'invalid',
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 628, in validate
      _, errors = self._do_load(data, many, partial=partial, postprocess=False)
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 670, in _do_load
      index_errors=self.opts.index_errors,
    File "/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py", line 292, in deserialize
      index=(index if index_errors else None)
    File "/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py", line 65, in call_and_store
      value = getter_func(data)
    File "/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py", line 285, in <lambda>
      data
    File "/_/env/lib/python3.7/site-packages/marshmallow/fields.py", line 265, in deserialize
      output = self._deserialize(value, attr, data)
    File "/_/env/lib/python3.7/site-packages/marshmallow/fields.py", line 465, in _deserialize
      data, errors = self.schema.load(value)
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 588, in load
      result, errors = self._do_load(data, many, partial=partial, postprocess=True)
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 674, in _do_load
      self._invoke_field_validators(unmarshal, data=result, many=many)
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 894, in _invoke_field_validators
      value = data[field_obj.attribute or field_name]
  TypeError: 'NoneType' object is not subscriptable
  ```
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  
  --- BEGIN FILE ---
  ```
  ### src/marshmallow/schema.py
  # -*- coding: utf-8 -*-
  """The :class:`Schema` class, including its metaclass and options (class Meta)."""
  from __future__ import absolute_import, unicode_literals
  
  from collections import defaultdict, namedtuple
  import copy
  import datetime as dt
  import decimal
  import inspect
  import json
  import uuid
  import warnings
  import functools
  
  from marshmallow import base, fields, utils, class_registry, marshalling
  from marshmallow.compat import (with_metaclass, iteritems, text_type,
                                  binary_type, Mapping, OrderedDict)
  from marshmallow.exceptions import ValidationError
  from marshmallow.orderedset import OrderedSet
  from marshmallow.decorators import (PRE_DUMP, POST_DUMP, PRE_LOAD, POST_LOAD,
                                      VALIDATES, VALIDATES_SCHEMA)
  from marshmallow.utils import missing
  from marshmallow.warnings import RemovedInMarshmallow3Warning, ChangedInMarshmallow3Warning
  
  
  #: Return type of :meth:`Schema.dump` including serialized data and errors
  MarshalResult = namedtuple('MarshalResult', ['data', 'errors'])
  #: Return type of :meth:`Schema.load`, including deserialized data and errors
  UnmarshalResult = namedtuple('UnmarshalResult', ['data', 'errors'])
  
  def _get_fields(attrs, field_class, pop=False, ordered=False):
      """Get fields from a class. If ordered=True, fields will sorted by creation index.
  
      :param attrs: Mapping of class attributes
      :param type field_class: Base field class
      :param bool pop: Remove matching fields
      """
      getter = getattr(attrs, 'pop' if pop else 'get')
      fields = [
          (field_name, getter(field_name))
          for field_name, field_value in list(iteritems(attrs))
          if utils.is_instance_or_subclass(field_value, field_class)
      ]
      if ordered:
          return sorted(
              fields,
              key=lambda pair: pair[1]._creation_index,
          )
      else:
          return fields
  
  # This function allows Schemas to inherit from non-Schema classes and ensures
  #   inheritance according to the MRO
  def _get_fields_by_mro(klass, field_class, ordered=False):
      """Collect fields from a class, following its method resolution order. The
      class itself is excluded from the search; only its parents are checked. Get
      fields from ``_declared_fields`` if available, else use ``__dict__``.
  
      :param type klass: Class whose fields to retrieve
      :param type field_class: Base field class
      """
      mro = inspect.getmro(klass)
      # Loop over mro in reverse to maintain correct order of fields
      return sum(
          (
              _get_fields(
                  getattr(base, '_declared_fields', base.__dict__),
                  field_class,
                  ordered=ordered
              )
              for base in mro[:0:-1]
          ),
          [],
      )
  
  
  class SchemaMeta(type):
      """Metaclass for the Schema class. Binds the declared fields to
      a ``_declared_fields`` attribute, which is a dictionary mapping attribute
      names to field objects. Also sets the ``opts`` class attribute, which is
      the Schema class's ``class Meta`` options.
      """
  
      def __new__(mcs, name, bases, attrs):
          meta = attrs.get('Meta')
          ordered = getattr(meta, 'ordered', False)
          if not ordered:
              # Inherit 'ordered' option
              # Warning: We loop through bases instead of MRO because we don't
              # yet have access to the class object
              # (i.e. can't call super before we have fields)
              for base_ in bases:
                  if hasattr(base_, 'Meta') and hasattr(base_.Meta, 'ordered'):
                      ordered = base_.Meta.ordered
                      break
              else:
                  ordered = False
          cls_fields = _get_fields(attrs, base.FieldABC, pop=True, ordered=ordered)
          klass = super(SchemaMeta, mcs).__new__(mcs, name, bases, attrs)
          inherited_fields = _get_fields_by_mro(klass, base.FieldABC, ordered=ordered)
  
          # Use getattr rather than attrs['Meta'] so that we get inheritance for free
          meta = getattr(klass, 'Meta')
          # Set klass.opts in __new__ rather than __init__ so that it is accessible in
          # get_declared_fields
          klass.opts = klass.OPTIONS_CLASS(meta)
          # Pass the inherited `ordered` into opts
          klass.opts.ordered = ordered
          # Add fields specifid in the `include` class Meta option
          cls_fields += list(klass.opts.include.items())
  
          dict_cls = OrderedDict if ordered else dict
          # Assign _declared_fields on class
          klass._declared_fields = mcs.get_declared_fields(
              klass=klass,
              cls_fields=cls_fields,
              inherited_fields=inherited_fields,
              dict_cls=dict_cls
          )
          return klass
  
      @classmethod
      def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls):
          """Returns a dictionary of field_name => `Field` pairs declard on the class.
          This is exposed mainly so that plugins can add additional fields, e.g. fields
          computed from class Meta options.
  
          :param type klass: The class object.
          :param dict cls_fields: The fields declared on the class, including those added
              by the ``include`` class Meta option.
          :param dict inherited_fileds: Inherited fields.
          :param type dict_class: Either `dict` or `OrderedDict`, depending on the whether
              the user specified `ordered=True`.
          """
          return dict_cls(inherited_fields + cls_fields)
  
      # NOTE: self is the class object
      def __init__(self, name, bases, attrs):
          super(SchemaMeta, self).__init__(name, bases, attrs)
          if name:
              class_registry.register(name, self)
          self._resolve_processors()
  
      def _resolve_processors(self):
          """Add in the decorated processors
  
          By doing this after constructing the class, we let standard inheritance
          do all the hard work.
          """
          mro = inspect.getmro(self)
          self._has_processors = False
          self.__processors__ = defaultdict(list)
          for attr_name in dir(self):
              # Need to look up the actual descriptor, not whatever might be
              # bound to the class. This needs to come from the __dict__ of the
              # declaring class.
              for parent in mro:
                  try:
                      attr = parent.__dict__[attr_name]
                  except KeyError:
                      continue
                  else:
                      break
              else:
                  # In case we didn't find the attribute and didn't break above.
                  # We should never hit this - it's just here for completeness
                  # to exclude the possibility of attr being undefined.
                  continue
  
              try:
                  processor_tags = attr.__marshmallow_tags__
              except AttributeError:
                  continue
  
              self._has_processors = bool(processor_tags)
              for tag in processor_tags:
                  # Use name here so we can get the bound method later, in case
                  # the processor was a descriptor or something.
                  self.__processors__[tag].append(attr_name)
  
  
  class SchemaOpts(object):
      """class Meta options for the :class:`Schema`. Defines defaults."""
  
      def __init__(self, meta):
          self.fields = getattr(meta, 'fields', ())
          if not isinstance(self.fields, (list, tuple)):
              raise ValueError("`fields` option must be a list or tuple.")
          self.additional = getattr(meta, 'additional', ())
          if not isinstance(self.additional, (list, tuple)):
              raise ValueError("`additional` option must be a list or tuple.")
          if self.fields and self.additional:
              raise ValueError("Cannot set both `fields` and `additional` options"
                              " for the same Schema.")
          self.exclude = getattr(meta, 'exclude', ())
          if not isinstance(self.exclude, (list, tuple)):
              raise ValueError("`exclude` must be a list or tuple.")
          self.strict = getattr(meta, 'strict', False)
          if hasattr(meta, 'dateformat'):
              warnings.warn(
                  "The dateformat option is renamed to datetimeformat in marshmallow 3.",
                  ChangedInMarshmallow3Warning
              )
          self.dateformat = getattr(meta, 'dateformat', None)
          if hasattr(meta, 'json_module'):
              warnings.warn(
                  "The json_module option is renamed to render_module in marshmallow 3.",
                  ChangedInMarshmallow3Warning
              )
          self.json_module = getattr(meta, 'json_module', json)
          if hasattr(meta, 'skip_missing'):
              warnings.warn(
                  'The skip_missing option is no longer necessary. Missing inputs passed to '
                  'Schema.dump will be excluded from the serialized output by default.',
                  UserWarning
              )
          self.ordered = getattr(meta, 'ordered', False)
          self.index_errors = getattr(meta, 'index_errors', True)
          self.include = getattr(meta, 'include', {})
          self.load_only = getattr(meta, 'load_only', ())
          self.dump_only = getattr(meta, 'dump_only', ())
  
  
  class BaseSchema(base.SchemaABC):
      """Base schema class with which to define custom schemas.
  
      Example usage:
  
      .. code-block:: python
  
          import datetime as dt
          from marshmallow import Schema, fields
  
          class Album(object):
              def __init__(self, title, release_date):
                  self.title = title
                  self.release_date = release_date
  
          class AlbumSchema(Schema):
              title = fields.Str()
              release_date = fields.Date()
  
          # Or, equivalently
          class AlbumSchema2(Schema):
              class Meta:
                  fields = ("title", "release_date")
  
          album = Album("Beggars Banquet", dt.date(1968, 12, 6))
          schema = AlbumSchema()
          data, errors = schema.dump(album)
          data  # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'}
  
      :param dict extra: A dict of extra attributes to bind to the serialized result.
      :param tuple|list only: Whitelist of fields to select when instantiating the Schema.
          If None, all fields are used.
          Nested fields can be represented with dot delimiters.
      :param tuple|list exclude: Blacklist of fields to exclude when instantiating the Schema.
          If a field appears in both `only` and `exclude`, it is not used.
          Nested fields can be represented with dot delimiters.
      :param str prefix: Optional prefix that will be prepended to all the
          serialized field names.
      :param bool strict: If `True`, raise errors if invalid data are passed in
          instead of failing silently and storing the errors.
      :param bool many: Should be set to `True` if ``obj`` is a collection
          so that the object will be serialized to a list.
      :param dict context: Optional context passed to :class:`fields.Method` and
          :class:`fields.Function` fields.
      :param tuple|list load_only: Fields to skip during serialization (write-only fields)
      :param tuple|list dump_only: Fields to skip during deserialization (read-only fields)
      :param bool|tuple partial: Whether to ignore missing fields. If its value
          is an iterable, only missing fields listed in that iterable will be
          ignored.
  
      .. versionchanged:: 2.0.0
          `__validators__`, `__preprocessors__`, and `__data_handlers__` are removed in favor of
          `marshmallow.decorators.validates_schema`,
          `marshmallow.decorators.pre_load` and `marshmallow.decorators.post_dump`.
          `__accessor__` and `__error_handler__` are deprecated. Implement the
          `handle_error` and `get_attribute` methods instead.
          """
      TYPE_MAPPING = {
          text_type: fields.String,
          binary_type: fields.String,
          dt.datetime: fields.DateTime,
          float: fields.Float,
          bool: fields.Boolean,
          tuple: fields.Raw,
          list: fields.Raw,
          set: fields.Raw,
          int: fields.Integer,
          uuid.UUID: fields.UUID,
          dt.time: fields.Time,
          dt.date: fields.Date,
          dt.timedelta: fields.TimeDelta,
          decimal.Decimal: fields.Decimal,
      }
  
      OPTIONS_CLASS = SchemaOpts
  
      #: DEPRECATED: Custom error handler function. May be `None`.
      __error_handler__ = None
      #: DEPRECATED: Function used to get values of an object.
      __accessor__ = None
  
      class Meta(object):
          """Options object for a Schema.
  
          Example usage: ::
  
              class Meta:
                  fields = ("id", "email", "date_created")
                  exclude = ("password", "secret_attribute")
  
          Available options:
  
          - ``fields``: Tuple or list of fields to include in the serialized result.
          - ``additional``: Tuple or list of fields to include *in addition* to the
              explicitly declared fields. ``additional`` and ``fields`` are
              mutually-exclusive options.
          - ``include``: Dictionary of additional fields to include in the schema. It is
              usually better to define fields as class variables, but you may need to
              use this option, e.g., if your fields are Python keywords. May be an
              `OrderedDict`.
          - ``exclude``: Tuple or list of fields to exclude in the serialized result.
              Nested fields can be represented with dot delimiters.
          - ``dateformat``: Date format for all DateTime fields that do not have their
              date format explicitly specified.
          - ``strict``: If `True`, raise errors during marshalling rather than
              storing them.
          - ``json_module``: JSON module to use for `loads` and `dumps`.
              Defaults to the ``json`` module in the stdlib.
          - ``ordered``: If `True`, order serialization output according to the
              order in which fields were declared. Output of `Schema.dump` will be a
              `collections.OrderedDict`.
          - ``index_errors``: If `True`, errors dictionaries will include the index
              of invalid items in a collection.
          - ``load_only``: Tuple or list of fields to exclude from serialized results.
          - ``dump_only``: Tuple or list of fields to exclude from deserialization
          """
          pass
  
      def __init__(self, extra=None, only=None, exclude=(), prefix='', strict=None,
                   many=False, context=None, load_only=(), dump_only=(),
                   partial=False):
          # copy declared fields from metaclass
          self.declared_fields = copy.deepcopy(self._declared_fields)
          self.many = many
          self.only = only
          self.exclude = set(self.opts.exclude) | set(exclude)
          if prefix:
              warnings.warn(
                  'The `prefix` argument is deprecated. Use a post_dump '
                  'method to insert a prefix instead.',
                  RemovedInMarshmallow3Warning
              )
          self.prefix = prefix
          self.strict = strict if strict is not None else self.opts.strict
          self.ordered = self.opts.ordered
          self.load_only = set(load_only) or set(self.opts.load_only)
          self.dump_only = set(dump_only) or set(self.opts.dump_only)
          self.partial = partial
          #: Dictionary mapping field_names -> :class:`Field` objects
          self.fields = self.dict_class()
          if extra:
              warnings.warn(
                  'The `extra` argument is deprecated. Use a post_dump '
                  'method to add additional data instead.',
                  RemovedInMarshmallow3Warning
              )
          self.extra = extra
          self.context = context or {}
          self._normalize_nested_options()
          self._types_seen = set()
          self._update_fields(many=many)
  
      def __repr__(self):
          return '<{ClassName}(many={self.many}, strict={self.strict})>'.format(
              ClassName=self.__class__.__name__, self=self
          )
  
      def _postprocess(self, data, many, obj):
          if self.extra:
              if many:
                  for each in data:
                      each.update(self.extra)
              else:
                  data.update(self.extra)
          return data
  
      @property
      def dict_class(self):
          return OrderedDict if self.ordered else dict
  
      @property
      def set_class(self):
          return OrderedSet if self.ordered else set
  
      ##### Override-able methods #####
  
      def handle_error(self, error, data):
          """Custom error handler function for the schema.
  
          :param ValidationError error: The `ValidationError` raised during (de)serialization.
          :param data: The original input data.
  
          .. versionadded:: 2.0.0
          """
          pass
  
      def get_attribute(self, attr, obj, default):
          """Defines how to pull values from an object to serialize.
  
          .. versionadded:: 2.0.0
          """
          return utils.get_value(attr, obj, default)
  
      ##### Handler decorators (deprecated) #####
  
      @classmethod
      def error_handler(cls, func):
          """Decorator that registers an error handler function for the schema.
          The function receives the :class:`Schema` instance, a dictionary of errors,
          and the serialized object (if serializing data) or data dictionary (if
          deserializing data) as arguments.
  
          Example: ::
  
              class UserSchema(Schema):
                  email = fields.Email()
  
              @UserSchema.error_handler
              def handle_errors(schema, errors, obj):
                  raise ValueError('An error occurred while marshalling {}'.format(obj))
  
              user = User(email='invalid')
              UserSchema().dump(user)  # => raises ValueError
              UserSchema().load({'email': 'bademail'})  # raises ValueError
  
          .. versionadded:: 0.7.0
          .. deprecated:: 2.0.0
              Set the ``error_handler`` class Meta option instead.
          """
          warnings.warn(
              'Schema.error_handler is deprecated. Set the error_handler class Meta option '
              'instead.', category=DeprecationWarning
          )
          cls.__error_handler__ = func
          return func
  
      @classmethod
      def accessor(cls, func):
          """Decorator that registers a function for pulling values from an object
          to serialize. The function receives the :class:`Schema` instance, the
          ``key`` of the value to get, the ``obj`` to serialize, and an optional
          ``default`` value.
  
          .. deprecated:: 2.0.0
              Set the ``error_handler`` class Meta option instead.
          """
          warnings.warn(
              'Schema.accessor is deprecated. Set the accessor class Meta option '
              'instead.', category=DeprecationWarning
          )
          cls.__accessor__ = func
          return func
  
      ##### Serialization/Deserialization API #####
  
      def dump(self, obj, many=None, update_fields=True, **kwargs):
          """Serialize an object to native Python data types according to this
          Schema's fields.
  
          :param obj: The object to serialize.
          :param bool many: Whether to serialize `obj` as a collection. If `None`, the value
              for `self.many` is used.
          :param bool update_fields: Whether to update the schema's field classes. Typically
              set to `True`, but may be `False` when serializing a homogenous collection.
              This parameter is used by `fields.Nested` to avoid multiple updates.
          :return: A tuple of the form (``data``, ``errors``)
          :rtype: `MarshalResult`, a `collections.namedtuple`
  
          .. versionadded:: 1.0.0
          """
          # Callable marshalling object
          marshal = marshalling.Marshaller(prefix=self.prefix)
          errors = {}
          many = self.many if many is None else bool(many)
          if many and utils.is_iterable_but_not_string(obj):
              obj = list(obj)
  
          if self._has_processors:
              try:
                  processed_obj = self._invoke_dump_processors(
                      PRE_DUMP,
                      obj,
                      many,
                      original_data=obj)
              except ValidationError as error:
                  errors = error.normalized_messages()
                  result = None
          else:
              processed_obj = obj
  
          if not errors:
              if update_fields:
                  obj_type = type(processed_obj)
                  if obj_type not in self._types_seen:
                      self._update_fields(processed_obj, many=many)
                      if not isinstance(processed_obj, Mapping):
                          self._types_seen.add(obj_type)
  
              try:
                  preresult = marshal(
                      processed_obj,
                      self.fields,
                      many=many,
                      # TODO: Remove self.__accessor__ in a later release
                      accessor=self.get_attribute or self.__accessor__,
                      dict_class=self.dict_class,
                      index_errors=self.opts.index_errors,
                      **kwargs
                  )
              except ValidationError as error:
                  errors = marshal.errors
                  preresult = error.data
  
              result = self._postprocess(preresult, many, obj=obj)
  
          if not errors and self._has_processors:
              try:
                  result = self._invoke_dump_processors(
                      POST_DUMP,
                      result,
                      many,
                      original_data=obj)
              except ValidationError as error:
                  errors = error.normalized_messages()
          if errors:
              # TODO: Remove self.__error_handler__ in a later release
              if self.__error_handler__ and callable(self.__error_handler__):
                  self.__error_handler__(errors, obj)
              exc = ValidationError(
                  errors,
                  field_names=marshal.error_field_names,
                  fields=marshal.error_fields,
                  data=obj,
                  **marshal.error_kwargs
              )
              self.handle_error(exc, obj)
              if self.strict:
                  raise exc
  
          return MarshalResult(result, errors)
  
      def dumps(self, obj, many=None, update_fields=True, *args, **kwargs):
          """Same as :meth:`dump`, except return a JSON-encoded string.
  
          :param obj: The object to serialize.
          :param bool many: Whether to serialize `obj` as a collection. If `None`, the value
              for `self.many` is used.
          :param bool update_fields: Whether to update the schema's field classes. Typically
              set to `True`, but may be `False` when serializing a homogenous collection.
              This parameter is used by `fields.Nested` to avoid multiple updates.
          :return: A tuple of the form (``data``, ``errors``)
          :rtype: `MarshalResult`, a `collections.namedtuple`
  
          .. versionadded:: 1.0.0
          """
          deserialized, errors = self.dump(obj, many=many, update_fields=update_fields)
          ret = self.opts.json_module.dumps(deserialized, *args, **kwargs)
          return MarshalResult(ret, errors)
  
      def load(self, data, many=None, partial=None):
          """Deserialize a data structure to an object defined by this Schema's
          fields and :meth:`make_object`.
  
          :param dict data: The data to deserialize.
          :param bool many: Whether to deserialize `data` as a collection. If `None`, the
              value for `self.many` is used.
          :param bool|tuple partial: Whether to ignore missing fields. If `None`,
              the value for `self.partial` is used. If its value is an iterable,
              only missing fields listed in that iterable will be ignored.
          :return: A tuple of the form (``data``, ``errors``)
          :rtype: `UnmarshalResult`, a `collections.namedtuple`
  
          .. versionadded:: 1.0.0
          """
          result, errors = self._do_load(data, many, partial=partial, postprocess=True)
          return UnmarshalResult(data=result, errors=errors)
  
      def loads(self, json_data, many=None, *args, **kwargs):
          """Same as :meth:`load`, except it takes a JSON string as input.
  
          :param str json_data: A JSON string of the data to deserialize.
          :param bool many: Whether to deserialize `obj` as a collection. If `None`, the
              value for `self.many` is used.
          :param bool|tuple partial: Whether to ignore missing fields. If `None`,
              the value for `self.partial` is used. If its value is an iterable,
              only missing fields listed in that iterable will be ignored.
          :return: A tuple of the form (``data``, ``errors``)
          :rtype: `UnmarshalResult`, a `collections.namedtuple`
  
          .. versionadded:: 1.0.0
          """
          # TODO: This avoids breaking backward compatibility if people were
          # passing in positional args after `many` for use by `json.loads`, but
          # ideally we shouldn't have to do this.
          partial = kwargs.pop('partial', None)
  
          data = self.opts.json_module.loads(json_data, *args, **kwargs)
          return self.load(data, many=many, partial=partial)
  
      def validate(self, data, many=None, partial=None):
          """Validate `data` against the schema, returning a dictionary of
          validation errors.
  
          :param dict data: The data to validate.
          :param bool many: Whether to validate `data` as a collection. If `None`, the
              value for `self.many` is used.
          :param bool|tuple partial: Whether to ignore missing fields. If `None`,
              the value for `self.partial` is used. If its value is an iterable,
              only missing fields listed in that iterable will be ignored.
          :return: A dictionary of validation errors.
          :rtype: dict
  
          .. versionadded:: 1.1.0
          """
          _, errors = self._do_load(data, many, partial=partial, postprocess=False)
          return errors
  
      ##### Private Helpers #####
  
      def _do_load(self, data, many=None, partial=None, postprocess=True):
          """Deserialize `data`, returning the deserialized result and a dictonary of
          validation errors.
  
          :param data: The data to deserialize.
          :param bool many: Whether to deserialize `data` as a collection. If `None`, the
              value for `self.many` is used.
          :param bool|tuple partial: Whether to validate required fields. If its value is an iterable,
              only fields listed in that iterable will be ignored will be allowed missing.
              If `True`, all fields will be allowed missing.
              If `None`, the value for `self.partial` is used.
          :param bool postprocess: Whether to run post_load methods..
          :return: A tuple of the form (`data`, `errors`)
          """
          # Callable unmarshalling object
          unmarshal = marshalling.Unmarshaller()
          errors = {}
          many = self.many if many is None else bool(many)
          if partial is None:
              partial = self.partial
          try:
              processed_data = self._invoke_load_processors(
                  PRE_LOAD,
                  data,
                  many,
                  original_data=data)
          except ValidationError as err:
              errors = err.normalized_messages()
              result = None
          if not errors:
              try:
                  result = unmarshal(
                      processed_data,
                      self.fields,
                      many=many,
                      partial=partial,
                      dict_class=self.dict_class,
                      index_errors=self.opts.index_errors,
                  )
              except ValidationError as error:
                  result = error.data
              self._invoke_field_validators(unmarshal, data=result, many=many)
              errors = unmarshal.errors
              field_errors = bool(errors)
              # Run schema-level migration
              try:
                  self._invoke_validators(unmarshal, pass_many=True, data=result, original_data=data,
                                          many=many, field_errors=field_errors)
              except ValidationError as err:
                  errors.update(err.messages)
              try:
                  self._invoke_validators(unmarshal, pass_many=False, data=result, original_data=data,
                                          many=many, field_errors=field_errors)
              except ValidationError as err:
                  errors.update(err.messages)
          # Run post processors
          if not errors and postprocess:
              try:
                  result = self._invoke_load_processors(
                      POST_LOAD,
                      result,
                      many,
                      original_data=data)
              except ValidationError as err:
                  errors = err.normalized_messages()
          if errors:
              # TODO: Remove self.__error_handler__ in a later release
              if self.__error_handler__ and callable(self.__error_handler__):
                  self.__error_handler__(errors, data)
              exc = ValidationError(
                  errors,
                  field_names=unmarshal.error_field_names,
                  fields=unmarshal.error_fields,
                  data=data,
                  **unmarshal.error_kwargs
              )
              self.handle_error(exc, data)
              if self.strict:
                  raise exc
  
          return result, errors
  
      def _normalize_nested_options(self):
          """Apply then flatten nested schema options"""
          if self.only is not None:
              # Apply the only option to nested fields.
              self.__apply_nested_option('only', self.only, 'intersection')
              # Remove the child field names from the only option.
              self.only = self.set_class(
                  [field.split('.', 1)[0] for field in self.only],
              )
          if self.exclude:
              # Apply the exclude option to nested fields.
              self.__apply_nested_option('exclude', self.exclude, 'union')
              # Remove the parent field names from the exclude option.
              self.exclude = self.set_class(
                  [field for field in self.exclude if '.' not in field],
              )
  
      def __apply_nested_option(self, option_name, field_names, set_operation):
          """Apply nested options to nested fields"""
          # Split nested field names on the first dot.
          nested_fields = [name.split('.', 1) for name in field_names if '.' in name]
          # Partition the nested field names by parent field.
          nested_options = defaultdict(list)
          for parent, nested_names in nested_fields:
              nested_options[parent].append(nested_names)
          # Apply the nested field options.
          for key, options in iter(nested_options.items()):
              new_options = self.set_class(options)
              original_options = getattr(self.declared_fields[key], option_name, ())
              if original_options:
                  if set_operation == 'union':
                      new_options |= self.set_class(original_options)
                  if set_operation == 'intersection':
                      new_options &= self.set_class(original_options)
              setattr(self.declared_fields[key], option_name, new_options)
  
      def _update_fields(self, obj=None, many=False):
          """Update fields based on the passed in object."""
          if self.only is not None:
              # Return only fields specified in only option
              if self.opts.fields:
                  field_names = self.set_class(self.opts.fields) & self.set_class(self.only)
              else:
                  field_names = self.set_class(self.only)
          elif self.opts.fields:
              # Return fields specified in fields option
              field_names = self.set_class(self.opts.fields)
          elif self.opts.additional:
              # Return declared fields + additional fields
              field_names = (self.set_class(self.declared_fields.keys()) |
                              self.set_class(self.opts.additional))
          else:
              field_names = self.set_class(self.declared_fields.keys())
  
          # If "exclude" option or param is specified, remove those fields
          field_names -= self.exclude
          ret = self.__filter_fields(field_names, obj, many=many)
          # Set parents
          self.__set_field_attrs(ret)
          self.fields = ret
          return self.fields
  
      def on_bind_field(self, field_name, field_obj):
          """Hook to modify a field when it is bound to the `Schema`. No-op by default."""
          return None
  
      def __set_field_attrs(self, fields_dict):
          """Bind fields to the schema, setting any necessary attributes
          on the fields (e.g. parent and name).
  
          Also set field load_only and dump_only values if field_name was
          specified in ``class Meta``.
          """
          for field_name, field_obj in iteritems(fields_dict):
              try:
                  if field_name in self.load_only:
                      field_obj.load_only = True
                  if field_name in self.dump_only:
                      field_obj.dump_only = True
                  field_obj._add_to_schema(field_name, self)
                  self.on_bind_field(field_name, field_obj)
              except TypeError:
                  # field declared as a class, not an instance
                  if (isinstance(field_obj, type) and
                          issubclass(field_obj, base.FieldABC)):
                      msg = ('Field for "{0}" must be declared as a '
                             'Field instance, not a class. '
                             'Did you mean "fields.{1}()"?'
                             .format(field_name, field_obj.__name__))
                      raise TypeError(msg)
          return fields_dict
  
      def __filter_fields(self, field_names, obj, many=False):
          """Return only those field_name:field_obj pairs specified by
          ``field_names``.
  
          :param set field_names: Field names to include in the final
              return dictionary.
          :param object|Mapping|list obj The object to base filtered fields on.
          :returns: An dict of field_name:field_obj pairs.
          """
          if obj and many:
              try:  # list
                  obj = obj[0]
              except IndexError:  # Nothing to serialize
                  return dict((k, v) for k, v in self.declared_fields.items() if k in field_names)
          ret = self.dict_class()
          for key in field_names:
              if key in self.declared_fields:
                  ret[key] = self.declared_fields[key]
              else:  # Implicit field creation (class Meta 'fields' or 'additional')
                  if obj:
                      attribute_type = None
                      try:
                          if isinstance(obj, Mapping):
                              attribute_type = type(obj[key])
                          else:
                              attribute_type = type(getattr(obj, key))
                      except (AttributeError, KeyError) as err:
                          err_type = type(err)
                          raise err_type(
                              '"{0}" is not a valid field for {1}.'.format(key, obj))
                      field_obj = self.TYPE_MAPPING.get(attribute_type, fields.Field)()
                  else:  # Object is None
                      field_obj = fields.Field()
                  # map key -> field (default to Raw)
                  ret[key] = field_obj
          return ret
  
      def _invoke_dump_processors(self, tag_name, data, many, original_data=None):
          # The pass_many post-dump processors may do things like add an envelope, so
          # invoke those after invoking the non-pass_many processors which will expect
          # to get a list of items.
          data = self._invoke_processors(tag_name, pass_many=False,
              data=data, many=many, original_data=original_data)
          data = self._invoke_processors(tag_name, pass_many=True,
              data=data, many=many, original_data=original_data)
          return data
  
      def _invoke_load_processors(self, tag_name, data, many, original_data=None):
          # This has to invert the order of the dump processors, so run the pass_many
          # processors first.
          data = self._invoke_processors(tag_name, pass_many=True,
              data=data, many=many, original_data=original_data)
          data = self._invoke_processors(tag_name, pass_many=False,
              data=data, many=many, original_data=original_data)
          return data
  
      def _invoke_field_validators(self, unmarshal, data, many):
          for attr_name in self.__processors__[(VALIDATES, False)]:
              validator = getattr(self, attr_name)
              validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATES, False)]
              field_name = validator_kwargs['field_name']
  
              try:
                  field_obj = self.fields[field_name]
              except KeyError:
                  if field_name in self.declared_fields:
                      continue
                  raise ValueError('"{0}" field does not exist.'.format(field_name))
  
              if many:
                  for idx, item in enumerate(data):
                      try:
                          value = item[field_obj.attribute or field_name]
                      except KeyError:
                          pass
                      else:
                          validated_value = unmarshal.call_and_store(
                              getter_func=validator,
                              data=value,
                              field_name=field_obj.load_from or field_name,
                              field_obj=field_obj,
                              index=(idx if self.opts.index_errors else None)
                          )
                          if validated_value is missing:
                              data[idx].pop(field_name, None)
              else:
                  try:
                      value = data[field_obj.attribute or field_name]
                  except KeyError:
                      pass
                  else:
                      validated_value = unmarshal.call_and_store(
                          getter_func=validator,
                          data=value,
                          field_name=field_obj.load_from or field_name,
                          field_obj=field_obj
                      )
                      if validated_value is missing:
                          data.pop(field_name, None)
  
      def _invoke_validators(
              self, unmarshal, pass_many, data, original_data, many, field_errors=False):
          errors = {}
          for attr_name in self.__processors__[(VALIDATES_SCHEMA, pass_many)]:
              validator = getattr(self, attr_name)
              validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATES_SCHEMA, pass_many)]
              pass_original = validator_kwargs.get('pass_original', False)
  
              skip_on_field_errors = validator_kwargs['skip_on_field_errors']
              if skip_on_field_errors and field_errors:
                  continue
  
              if pass_many:
                  validator = functools.partial(validator, many=many)
              if many and not pass_many:
                  for idx, item in enumerate(data):
                      try:
                          unmarshal.run_validator(validator,
                                                  item, original_data, self.fields, many=many,
                                                  index=idx, pass_original=pass_original)
                      except ValidationError as err:
                          errors.update(err.messages)
              else:
                  try:
                      unmarshal.run_validator(validator,
                                              data, original_data, self.fields, many=many,
                                              pass_original=pass_original)
                  except ValidationError as err:
                      errors.update(err.messages)
          if errors:
              raise ValidationError(errors)
          return None
  
      def _invoke_processors(self, tag_name, pass_many, data, many, original_data=None):
          for attr_name in self.__processors__[(tag_name, pass_many)]:
              # This will be a bound method.
              processor = getattr(self, attr_name)
  
              processor_kwargs = processor.__marshmallow_kwargs__[(tag_name, pass_many)]
              pass_original = processor_kwargs.get('pass_original', False)
  
              if pass_many:
                  if pass_original:
                      data = utils.if_none(processor(data, many, original_data), data)
                  else:
                      data = utils.if_none(processor(data, many), data)
              elif many:
                  if pass_original:
                      data = [utils.if_none(processor(item, original_data), item)
                              for item in data]
                  else:
                      data = [utils.if_none(processor(item), item) for item in data]
              else:
                  if pass_original:
                      data = utils.if_none(processor(data, original_data), data)
                  else:
                      data = utils.if_none(processor(data), data)
          return data
  
  
  class Schema(with_metaclass(SchemaMeta, BaseSchema)):
      __doc__ = BaseSchema.__doc__
  
  ```
  --- END FILE ---
  
  Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.
  
  Every *SEARCH/REPLACE* edit must use this format:
  1. The file path
  2. The start of search block: <<<<<<< SEARCH
  3. A contiguous chunk of lines to search for in the existing source code
  4. The dividing line: =======
  5. The lines to replace into the source code
  6. The end of the replace block: >>>>>>> REPLACE
  
  Here is an example:
  
  ```python
  ### mathweb/flask/app.py
  <<<<<<< SEARCH
  from flask import Flask
  =======
  import math
  from flask import Flask
  >>>>>>> REPLACE
  ```
  
  Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
  Wrap the *SEARCH/REPLACE* edit in blocks ```python...```.
  
instance: {"FAIL_TO_PASS": "[\"tests/test_marshalling.py::TestUnmarshaller::test_deserialize_wrong_nested_type_with_validates_method\"]", "PASS_TO_PASS": "[\"tests/test_marshalling.py::test_missing_is_falsy\", \"tests/test_marshalling.py::TestMarshaller::test_prefix\", \"tests/test_marshalling.py::TestMarshaller::test_marshalling_generator\", \"tests/test_marshalling.py::TestMarshaller::test_default_to_missing\", \"tests/test_marshalling.py::TestMarshaller::test_serialize_fields_with_load_only_param\", \"tests/test_marshalling.py::TestMarshaller::test_missing_data_are_skipped\", \"tests/test_marshalling.py::TestMarshaller::test_serialize_with_load_only_doesnt_validate\", \"tests/test_marshalling.py::TestMarshaller::test_serialize_fields_with_dump_to_param\", \"tests/test_marshalling.py::TestMarshaller::test_serialize_fields_with_dump_to_and_prefix_params\", \"tests/test_marshalling.py::TestMarshaller::test_stores_indices_of_errors_when_many_equals_true\", \"tests/test_marshalling.py::TestMarshaller::test_doesnt_store_errors_when_index_errors_equals_false\", \"tests/test_marshalling.py::TestUnmarshaller::test_extra_data_is_ignored\", \"tests/test_marshalling.py::TestUnmarshaller::test_stores_errors\", \"tests/test_marshalling.py::TestUnmarshaller::test_stores_indices_of_errors_when_many_equals_true\", \"tests/test_marshalling.py::TestUnmarshaller::test_doesnt_store_errors_when_index_errors_equals_false\", \"tests/test_marshalling.py::TestUnmarshaller::test_deserialize\", \"tests/test_marshalling.py::TestUnmarshaller::test_extra_fields\", \"tests/test_marshalling.py::TestUnmarshaller::test_deserialize_many\", \"tests/test_marshalling.py::TestUnmarshaller::test_deserialize_stores_errors\", \"tests/test_marshalling.py::TestUnmarshaller::test_deserialize_fields_with_attribute_param\", \"tests/test_marshalling.py::TestUnmarshaller::test_deserialize_fields_with_load_from_param\", \"tests/test_marshalling.py::TestUnmarshaller::test_deserialize_fields_with_dump_only_param\", \"tests/test_marshalling.py::TestUnmarshaller::test_deserialize_wrong_type_root_data\", \"tests/test_marshalling.py::TestUnmarshaller::test_deserialize_wrong_type_nested_data\"]", "base_commit": "2be2d83a1a9a6d3d9b85804f3ab545cecc409bb0", "created_at": "2019-08-13T04:36:01Z", "environment_setup_commit": "7015fc4333a2f32cd58c3465296e834acd4496ff", "hints_text": "Thanks for reporting. I was able to reproduce this on 2.20.0. This is likely a regression from https://github.com/marshmallow-code/marshmallow/pull/1323 . I don't have time to look into it now. Would appreciate a PR.", "instance_id": "marshmallow-code__marshmallow-1343", "patch": "diff --git a/src/marshmallow/schema.py b/src/marshmallow/schema.py\n--- a/src/marshmallow/schema.py\n+++ b/src/marshmallow/schema.py\n@@ -877,7 +877,7 @@ def _invoke_field_validators(self, unmarshal, data, many):\n                 for idx, item in enumerate(data):\n                     try:\n                         value = item[field_obj.attribute or field_name]\n-                    except KeyError:\n+                    except (KeyError, TypeError):\n                         pass\n                     else:\n                         validated_value = unmarshal.call_and_store(\n@@ -892,7 +892,7 @@ def _invoke_field_validators(self, unmarshal, data, many):\n             else:\n                 try:\n                     value = data[field_obj.attribute or field_name]\n-                except KeyError:\n+                except (KeyError, TypeError):\n                     pass\n                 else:\n                     validated_value = unmarshal.call_and_store(\n", "problem_statement": "[version 2.20.0] TypeError: 'NoneType' object is not subscriptable\nAfter update from version 2.19.5 to 2.20.0 I got error for code like:\r\n\r\n```python\r\nfrom marshmallow import Schema, fields, validates\r\n\r\n\r\nclass Bar(Schema):\r\n    value = fields.String()\r\n\r\n    @validates('value')  # <- issue here\r\n    def validate_value(self, value):\r\n        pass\r\n\r\n\r\nclass Foo(Schema):\r\n    bar = fields.Nested(Bar)\r\n\r\n\r\nsch = Foo()\r\n\r\nsch.validate({\r\n    'bar': 'invalid',\r\n})\r\n```\r\n\r\n```\r\nTraceback (most recent call last):\r\n  File \"/_/bug_mschema.py\", line 19, in <module>\r\n    'bar': 'invalid',\r\n  File \"/_/env/lib/python3.7/site-packages/marshmallow/schema.py\", line 628, in validate\r\n    _, errors = self._do_load(data, many, partial=partial, postprocess=False)\r\n  File \"/_/env/lib/python3.7/site-packages/marshmallow/schema.py\", line 670, in _do_load\r\n    index_errors=self.opts.index_errors,\r\n  File \"/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py\", line 292, in deserialize\r\n    index=(index if index_errors else None)\r\n  File \"/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py\", line 65, in call_and_store\r\n    value = getter_func(data)\r\n  File \"/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py\", line 285, in <lambda>\r\n    data\r\n  File \"/_/env/lib/python3.7/site-packages/marshmallow/fields.py\", line 265, in deserialize\r\n    output = self._deserialize(value, attr, data)\r\n  File \"/_/env/lib/python3.7/site-packages/marshmallow/fields.py\", line 465, in _deserialize\r\n    data, errors = self.schema.load(value)\r\n  File \"/_/env/lib/python3.7/site-packages/marshmallow/schema.py\", line 588, in load\r\n    result, errors = self._do_load(data, many, partial=partial, postprocess=True)\r\n  File \"/_/env/lib/python3.7/site-packages/marshmallow/schema.py\", line 674, in _do_load\r\n    self._invoke_field_validators(unmarshal, data=result, many=many)\r\n  File \"/_/env/lib/python3.7/site-packages/marshmallow/schema.py\", line 894, in _invoke_field_validators\r\n    value = data[field_obj.attribute or field_name]\r\nTypeError: 'NoneType' object is not subscriptable\r\n```\n", "repo": "marshmallow-code/marshmallow", "test_patch": "diff --git a/tests/test_marshalling.py b/tests/test_marshalling.py\n--- a/tests/test_marshalling.py\n+++ b/tests/test_marshalling.py\n@@ -2,7 +2,7 @@\n \n import pytest\n \n-from marshmallow import fields, Schema\n+from marshmallow import fields, Schema, validates\n from marshmallow.marshalling import Marshaller, Unmarshaller, missing\n from marshmallow.exceptions import ValidationError\n \n@@ -283,3 +283,24 @@ class TestSchema(Schema):\n \n             assert result is None\n             assert excinfo.value.messages == {'foo': {'_schema': ['Invalid input type.']}}\n+\n+    # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1342\n+    def test_deserialize_wrong_nested_type_with_validates_method(self, unmarshal):\n+        class TestSchema(Schema):\n+            value = fields.String()\n+\n+            @validates('value')\n+            def validate_value(self, value):\n+                pass\n+\n+        data = {\n+            'foo': 'not what we need'\n+        }\n+        fields_dict = {\n+            'foo': fields.Nested(TestSchema, required=True)\n+        }\n+        with pytest.raises(ValidationError) as excinfo:\n+            result = unmarshal.deserialize(data, fields_dict)\n+\n+            assert result is None\n+            assert excinfo.value.messages == {'foo': {'_schema': ['Invalid input type.']}}\n", "version": "2.20"}
parsed_commit_content: {"file_diffs":[{"old_file_content":"# -*- coding: utf-8 -*-\n\"\"\"The :class:`Schema` class, including its metaclass and options (class Meta).\"\"\"\nfrom __future__ import absolute_import, unicode_literals\n\nfrom collections import defaultdict, namedtuple\nimport copy\nimport datetime as dt\nimport decimal\nimport inspect\nimport json\nimport uuid\nimport warnings\nimport functools\n\nfrom marshmallow import base, fields, utils, class_registry, marshalling\nfrom marshmallow.compat import (with_metaclass, iteritems, text_type,\n                                binary_type, Mapping, OrderedDict)\nfrom marshmallow.exceptions import ValidationError\nfrom marshmallow.orderedset import OrderedSet\nfrom marshmallow.decorators import (PRE_DUMP, POST_DUMP, PRE_LOAD, POST_LOAD,\n                                    VALIDATES, VALIDATES_SCHEMA)\nfrom marshmallow.utils import missing\nfrom marshmallow.warnings import RemovedInMarshmallow3Warning, ChangedInMarshmallow3Warning\n\n\n#: Return type of :meth:`Schema.dump` including serialized data and errors\nMarshalResult = namedtuple('MarshalResult', ['data', 'errors'])\n#: Return type of :meth:`Schema.load`, including deserialized data and errors\nUnmarshalResult = namedtuple('UnmarshalResult', ['data', 'errors'])\n\ndef _get_fields(attrs, field_class, pop=False, ordered=False):\n    \"\"\"Get fields from a class. If ordered=True, fields will sorted by creation index.\n\n    :param attrs: Mapping of class attributes\n    :param type field_class: Base field class\n    :param bool pop: Remove matching fields\n    \"\"\"\n    getter = getattr(attrs, 'pop' if pop else 'get')\n    fields = [\n        (field_name, getter(field_name))\n        for field_name, field_value in list(iteritems(attrs))\n        if utils.is_instance_or_subclass(field_value, field_class)\n    ]\n    if ordered:\n        return sorted(\n            fields,\n            key=lambda pair: pair[1]._creation_index,\n        )\n    else:\n        return fields\n\n# This function allows Schemas to inherit from non-Schema classes and ensures\n#   inheritance according to the MRO\ndef _get_fields_by_mro(klass, field_class, ordered=False):\n    \"\"\"Collect fields from a class, following its method resolution order. The\n    class itself is excluded from the search; only its parents are checked. Get\n    fields from ``_declared_fields`` if available, else use ``__dict__``.\n\n    :param type klass: Class whose fields to retrieve\n    :param type field_class: Base field class\n    \"\"\"\n    mro = inspect.getmro(klass)\n    # Loop over mro in reverse to maintain correct order of fields\n    return sum(\n        (\n            _get_fields(\n                getattr(base, '_declared_fields', base.__dict__),\n                field_class,\n                ordered=ordered\n            )\n            for base in mro[:0:-1]\n        ),\n        [],\n    )\n\n\nclass SchemaMeta(type):\n    \"\"\"Metaclass for the Schema class. Binds the declared fields to\n    a ``_declared_fields`` attribute, which is a dictionary mapping attribute\n    names to field objects. Also sets the ``opts`` class attribute, which is\n    the Schema class's ``class Meta`` options.\n    \"\"\"\n\n    def __new__(mcs, name, bases, attrs):\n        meta = attrs.get('Meta')\n        ordered = getattr(meta, 'ordered', False)\n        if not ordered:\n            # Inherit 'ordered' option\n            # Warning: We loop through bases instead of MRO because we don't\n            # yet have access to the class object\n            # (i.e. can't call super before we have fields)\n            for base_ in bases:\n                if hasattr(base_, 'Meta') and hasattr(base_.Meta, 'ordered'):\n                    ordered = base_.Meta.ordered\n                    break\n            else:\n                ordered = False\n        cls_fields = _get_fields(attrs, base.FieldABC, pop=True, ordered=ordered)\n        klass = super(SchemaMeta, mcs).__new__(mcs, name, bases, attrs)\n        inherited_fields = _get_fields_by_mro(klass, base.FieldABC, ordered=ordered)\n\n        # Use getattr rather than attrs['Meta'] so that we get inheritance for free\n        meta = getattr(klass, 'Meta')\n        # Set klass.opts in __new__ rather than __init__ so that it is accessible in\n        # get_declared_fields\n        klass.opts = klass.OPTIONS_CLASS(meta)\n        # Pass the inherited `ordered` into opts\n        klass.opts.ordered = ordered\n        # Add fields specifid in the `include` class Meta option\n        cls_fields += list(klass.opts.include.items())\n\n        dict_cls = OrderedDict if ordered else dict\n        # Assign _declared_fields on class\n        klass._declared_fields = mcs.get_declared_fields(\n            klass=klass,\n            cls_fields=cls_fields,\n            inherited_fields=inherited_fields,\n            dict_cls=dict_cls\n        )\n        return klass\n\n    @classmethod\n    def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls):\n        \"\"\"Returns a dictionary of field_name => `Field` pairs declard on the class.\n        This is exposed mainly so that plugins can add additional fields, e.g. fields\n        computed from class Meta options.\n\n        :param type klass: The class object.\n        :param dict cls_fields: The fields declared on the class, including those added\n            by the ``include`` class Meta option.\n        :param dict inherited_fileds: Inherited fields.\n        :param type dict_class: Either `dict` or `OrderedDict`, depending on the whether\n            the user specified `ordered=True`.\n        \"\"\"\n        return dict_cls(inherited_fields + cls_fields)\n\n    # NOTE: self is the class object\n    def __init__(self, name, bases, attrs):\n        super(SchemaMeta, self).__init__(name, bases, attrs)\n        if name:\n            class_registry.register(name, self)\n        self._resolve_processors()\n\n    def _resolve_processors(self):\n        \"\"\"Add in the decorated processors\n\n        By doing this after constructing the class, we let standard inheritance\n        do all the hard work.\n        \"\"\"\n        mro = inspect.getmro(self)\n        self._has_processors = False\n        self.__processors__ = defaultdict(list)\n        for attr_name in dir(self):\n            # Need to look up the actual descriptor, not whatever might be\n            # bound to the class. This needs to come from the __dict__ of the\n            # declaring class.\n            for parent in mro:\n                try:\n                    attr = parent.__dict__[attr_name]\n                except KeyError:\n                    continue\n                else:\n                    break\n            else:\n                # In case we didn't find the attribute and didn't break above.\n                # We should never hit this - it's just here for completeness\n                # to exclude the possibility of attr being undefined.\n                continue\n\n            try:\n                processor_tags = attr.__marshmallow_tags__\n            except AttributeError:\n                continue\n\n            self._has_processors = bool(processor_tags)\n            for tag in processor_tags:\n                # Use name here so we can get the bound method later, in case\n                # the processor was a descriptor or something.\n                self.__processors__[tag].append(attr_name)\n\n\nclass SchemaOpts(object):\n    \"\"\"class Meta options for the :class:`Schema`. Defines defaults.\"\"\"\n\n    def __init__(self, meta):\n        self.fields = getattr(meta, 'fields', ())\n        if not isinstance(self.fields, (list, tuple)):\n            raise ValueError(\"`fields` option must be a list or tuple.\")\n        self.additional = getattr(meta, 'additional', ())\n        if not isinstance(self.additional, (list, tuple)):\n            raise ValueError(\"`additional` option must be a list or tuple.\")\n        if self.fields and self.additional:\n            raise ValueError(\"Cannot set both `fields` and `additional` options\"\n                            \" for the same Schema.\")\n        self.exclude = getattr(meta, 'exclude', ())\n        if not isinstance(self.exclude, (list, tuple)):\n            raise ValueError(\"`exclude` must be a list or tuple.\")\n        self.strict = getattr(meta, 'strict', False)\n        if hasattr(meta, 'dateformat'):\n            warnings.warn(\n                \"The dateformat option is renamed to datetimeformat in marshmallow 3.\",\n                ChangedInMarshmallow3Warning\n            )\n        self.dateformat = getattr(meta, 'dateformat', None)\n        if hasattr(meta, 'json_module'):\n            warnings.warn(\n                \"The json_module option is renamed to render_module in marshmallow 3.\",\n                ChangedInMarshmallow3Warning\n            )\n        self.json_module = getattr(meta, 'json_module', json)\n        if hasattr(meta, 'skip_missing'):\n            warnings.warn(\n                'The skip_missing option is no longer necessary. Missing inputs passed to '\n                'Schema.dump will be excluded from the serialized output by default.',\n                UserWarning\n            )\n        self.ordered = getattr(meta, 'ordered', False)\n        self.index_errors = getattr(meta, 'index_errors', True)\n        self.include = getattr(meta, 'include', {})\n        self.load_only = getattr(meta, 'load_only', ())\n        self.dump_only = getattr(meta, 'dump_only', ())\n\n\nclass BaseSchema(base.SchemaABC):\n    \"\"\"Base schema class with which to define custom schemas.\n\n    Example usage:\n\n    .. code-block:: python\n\n        import datetime as dt\n        from marshmallow import Schema, fields\n\n        class Album(object):\n            def __init__(self, title, release_date):\n                self.title = title\n                self.release_date = release_date\n\n        class AlbumSchema(Schema):\n            title = fields.Str()\n            release_date = fields.Date()\n\n        # Or, equivalently\n        class AlbumSchema2(Schema):\n            class Meta:\n                fields = (\"title\", \"release_date\")\n\n        album = Album(\"Beggars Banquet\", dt.date(1968, 12, 6))\n        schema = AlbumSchema()\n        data, errors = schema.dump(album)\n        data  # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'}\n\n    :param dict extra: A dict of extra attributes to bind to the serialized result.\n    :param tuple|list only: Whitelist of fields to select when instantiating the Schema.\n        If None, all fields are used.\n        Nested fields can be represented with dot delimiters.\n    :param tuple|list exclude: Blacklist of fields to exclude when instantiating the Schema.\n        If a field appears in both `only` and `exclude`, it is not used.\n        Nested fields can be represented with dot delimiters.\n    :param str prefix: Optional prefix that will be prepended to all the\n        serialized field names.\n    :param bool strict: If `True`, raise errors if invalid data are passed in\n        instead of failing silently and storing the errors.\n    :param bool many: Should be set to `True` if ``obj`` is a collection\n        so that the object will be serialized to a list.\n    :param dict context: Optional context passed to :class:`fields.Method` and\n        :class:`fields.Function` fields.\n    :param tuple|list load_only: Fields to skip during serialization (write-only fields)\n    :param tuple|list dump_only: Fields to skip during deserialization (read-only fields)\n    :param bool|tuple partial: Whether to ignore missing fields. If its value\n        is an iterable, only missing fields listed in that iterable will be\n        ignored.\n\n    .. versionchanged:: 2.0.0\n        `__validators__`, `__preprocessors__`, and `__data_handlers__` are removed in favor of\n        `marshmallow.decorators.validates_schema`,\n        `marshmallow.decorators.pre_load` and `marshmallow.decorators.post_dump`.\n        `__accessor__` and `__error_handler__` are deprecated. Implement the\n        `handle_error` and `get_attribute` methods instead.\n        \"\"\"\n    TYPE_MAPPING = {\n        text_type: fields.String,\n        binary_type: fields.String,\n        dt.datetime: fields.DateTime,\n        float: fields.Float,\n        bool: fields.Boolean,\n        tuple: fields.Raw,\n        list: fields.Raw,\n        set: fields.Raw,\n        int: fields.Integer,\n        uuid.UUID: fields.UUID,\n        dt.time: fields.Time,\n        dt.date: fields.Date,\n        dt.timedelta: fields.TimeDelta,\n        decimal.Decimal: fields.Decimal,\n    }\n\n    OPTIONS_CLASS = SchemaOpts\n\n    #: DEPRECATED: Custom error handler function. May be `None`.\n    __error_handler__ = None\n    #: DEPRECATED: Function used to get values of an object.\n    __accessor__ = None\n\n    class Meta(object):\n        \"\"\"Options object for a Schema.\n\n        Example usage: ::\n\n            class Meta:\n                fields = (\"id\", \"email\", \"date_created\")\n                exclude = (\"password\", \"secret_attribute\")\n\n        Available options:\n\n        - ``fields``: Tuple or list of fields to include in the serialized result.\n        - ``additional``: Tuple or list of fields to include *in addition* to the\n            explicitly declared fields. ``additional`` and ``fields`` are\n            mutually-exclusive options.\n        - ``include``: Dictionary of additional fields to include in the schema. It is\n            usually better to define fields as class variables, but you may need to\n            use this option, e.g., if your fields are Python keywords. May be an\n            `OrderedDict`.\n        - ``exclude``: Tuple or list of fields to exclude in the serialized result.\n            Nested fields can be represented with dot delimiters.\n        - ``dateformat``: Date format for all DateTime fields that do not have their\n            date format explicitly specified.\n        - ``strict``: If `True`, raise errors during marshalling rather than\n            storing them.\n        - ``json_module``: JSON module to use for `loads` and `dumps`.\n            Defaults to the ``json`` module in the stdlib.\n        - ``ordered``: If `True`, order serialization output according to the\n            order in which fields were declared. Output of `Schema.dump` will be a\n            `collections.OrderedDict`.\n        - ``index_errors``: If `True`, errors dictionaries will include the index\n            of invalid items in a collection.\n        - ``load_only``: Tuple or list of fields to exclude from serialized results.\n        - ``dump_only``: Tuple or list of fields to exclude from deserialization\n        \"\"\"\n        pass\n\n    def __init__(self, extra=None, only=None, exclude=(), prefix='', strict=None,\n                 many=False, context=None, load_only=(), dump_only=(),\n                 partial=False):\n        # copy declared fields from metaclass\n        self.declared_fields = copy.deepcopy(self._declared_fields)\n        self.many = many\n        self.only = only\n        self.exclude = set(self.opts.exclude) | set(exclude)\n        if prefix:\n            warnings.warn(\n                'The `prefix` argument is deprecated. Use a post_dump '\n                'method to insert a prefix instead.',\n                RemovedInMarshmallow3Warning\n            )\n        self.prefix = prefix\n        self.strict = strict if strict is not None else self.opts.strict\n        self.ordered = self.opts.ordered\n        self.load_only = set(load_only) or set(self.opts.load_only)\n        self.dump_only = set(dump_only) or set(self.opts.dump_only)\n        self.partial = partial\n        #: Dictionary mapping field_names -> :class:`Field` objects\n        self.fields = self.dict_class()\n        if extra:\n            warnings.warn(\n                'The `extra` argument is deprecated. Use a post_dump '\n                'method to add additional data instead.',\n                RemovedInMarshmallow3Warning\n            )\n        self.extra = extra\n        self.context = context or {}\n        self._normalize_nested_options()\n        self._types_seen = set()\n        self._update_fields(many=many)\n\n    def __repr__(self):\n        return '<{ClassName}(many={self.many}, strict={self.strict})>'.format(\n            ClassName=self.__class__.__name__, self=self\n        )\n\n    def _postprocess(self, data, many, obj):\n        if self.extra:\n            if many:\n                for each in data:\n                    each.update(self.extra)\n            else:\n                data.update(self.extra)\n        return data\n\n    @property\n    def dict_class(self):\n        return OrderedDict if self.ordered else dict\n\n    @property\n    def set_class(self):\n        return OrderedSet if self.ordered else set\n\n    ##### Override-able methods #####\n\n    def handle_error(self, error, data):\n        \"\"\"Custom error handler function for the schema.\n\n        :param ValidationError error: The `ValidationError` raised during (de)serialization.\n        :param data: The original input data.\n\n        .. versionadded:: 2.0.0\n        \"\"\"\n        pass\n\n    def get_attribute(self, attr, obj, default):\n        \"\"\"Defines how to pull values from an object to serialize.\n\n        .. versionadded:: 2.0.0\n        \"\"\"\n        return utils.get_value(attr, obj, default)\n\n    ##### Handler decorators (deprecated) #####\n\n    @classmethod\n    def error_handler(cls, func):\n        \"\"\"Decorator that registers an error handler function for the schema.\n        The function receives the :class:`Schema` instance, a dictionary of errors,\n        and the serialized object (if serializing data) or data dictionary (if\n        deserializing data) as arguments.\n\n        Example: ::\n\n            class UserSchema(Schema):\n                email = fields.Email()\n\n            @UserSchema.error_handler\n            def handle_errors(schema, errors, obj):\n                raise ValueError('An error occurred while marshalling {}'.format(obj))\n\n            user = User(email='invalid')\n            UserSchema().dump(user)  # => raises ValueError\n            UserSchema().load({'email': 'bademail'})  # raises ValueError\n\n        .. versionadded:: 0.7.0\n        .. deprecated:: 2.0.0\n            Set the ``error_handler`` class Meta option instead.\n        \"\"\"\n        warnings.warn(\n            'Schema.error_handler is deprecated. Set the error_handler class Meta option '\n            'instead.', category=DeprecationWarning\n        )\n        cls.__error_handler__ = func\n        return func\n\n    @classmethod\n    def accessor(cls, func):\n        \"\"\"Decorator that registers a function for pulling values from an object\n        to serialize. The function receives the :class:`Schema` instance, the\n        ``key`` of the value to get, the ``obj`` to serialize, and an optional\n        ``default`` value.\n\n        .. deprecated:: 2.0.0\n            Set the ``error_handler`` class Meta option instead.\n        \"\"\"\n        warnings.warn(\n            'Schema.accessor is deprecated. Set the accessor class Meta option '\n            'instead.', category=DeprecationWarning\n        )\n        cls.__accessor__ = func\n        return func\n\n    ##### Serialization/Deserialization API #####\n\n    def dump(self, obj, many=None, update_fields=True, **kwargs):\n        \"\"\"Serialize an object to native Python data types according to this\n        Schema's fields.\n\n        :param obj: The object to serialize.\n        :param bool many: Whether to serialize `obj` as a collection. If `None`, the value\n            for `self.many` is used.\n        :param bool update_fields: Whether to update the schema's field classes. Typically\n            set to `True`, but may be `False` when serializing a homogenous collection.\n            This parameter is used by `fields.Nested` to avoid multiple updates.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `MarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        # Callable marshalling object\n        marshal = marshalling.Marshaller(prefix=self.prefix)\n        errors = {}\n        many = self.many if many is None else bool(many)\n        if many and utils.is_iterable_but_not_string(obj):\n            obj = list(obj)\n\n        if self._has_processors:\n            try:\n                processed_obj = self._invoke_dump_processors(\n                    PRE_DUMP,\n                    obj,\n                    many,\n                    original_data=obj)\n            except ValidationError as error:\n                errors = error.normalized_messages()\n                result = None\n        else:\n            processed_obj = obj\n\n        if not errors:\n            if update_fields:\n                obj_type = type(processed_obj)\n                if obj_type not in self._types_seen:\n                    self._update_fields(processed_obj, many=many)\n                    if not isinstance(processed_obj, Mapping):\n                        self._types_seen.add(obj_type)\n\n            try:\n                preresult = marshal(\n                    processed_obj,\n                    self.fields,\n                    many=many,\n                    # TODO: Remove self.__accessor__ in a later release\n                    accessor=self.get_attribute or self.__accessor__,\n                    dict_class=self.dict_class,\n                    index_errors=self.opts.index_errors,\n                    **kwargs\n                )\n            except ValidationError as error:\n                errors = marshal.errors\n                preresult = error.data\n\n            result = self._postprocess(preresult, many, obj=obj)\n\n        if not errors and self._has_processors:\n            try:\n                result = self._invoke_dump_processors(\n                    POST_DUMP,\n                    result,\n                    many,\n                    original_data=obj)\n            except ValidationError as error:\n                errors = error.normalized_messages()\n        if errors:\n            # TODO: Remove self.__error_handler__ in a later release\n            if self.__error_handler__ and callable(self.__error_handler__):\n                self.__error_handler__(errors, obj)\n            exc = ValidationError(\n                errors,\n                field_names=marshal.error_field_names,\n                fields=marshal.error_fields,\n                data=obj,\n                **marshal.error_kwargs\n            )\n            self.handle_error(exc, obj)\n            if self.strict:\n                raise exc\n\n        return MarshalResult(result, errors)\n\n    def dumps(self, obj, many=None, update_fields=True, *args, **kwargs):\n        \"\"\"Same as :meth:`dump`, except return a JSON-encoded string.\n\n        :param obj: The object to serialize.\n        :param bool many: Whether to serialize `obj` as a collection. If `None`, the value\n            for `self.many` is used.\n        :param bool update_fields: Whether to update the schema's field classes. Typically\n            set to `True`, but may be `False` when serializing a homogenous collection.\n            This parameter is used by `fields.Nested` to avoid multiple updates.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `MarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        deserialized, errors = self.dump(obj, many=many, update_fields=update_fields)\n        ret = self.opts.json_module.dumps(deserialized, *args, **kwargs)\n        return MarshalResult(ret, errors)\n\n    def load(self, data, many=None, partial=None):\n        \"\"\"Deserialize a data structure to an object defined by this Schema's\n        fields and :meth:`make_object`.\n\n        :param dict data: The data to deserialize.\n        :param bool many: Whether to deserialize `data` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to ignore missing fields. If `None`,\n            the value for `self.partial` is used. If its value is an iterable,\n            only missing fields listed in that iterable will be ignored.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `UnmarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        result, errors = self._do_load(data, many, partial=partial, postprocess=True)\n        return UnmarshalResult(data=result, errors=errors)\n\n    def loads(self, json_data, many=None, *args, **kwargs):\n        \"\"\"Same as :meth:`load`, except it takes a JSON string as input.\n\n        :param str json_data: A JSON string of the data to deserialize.\n        :param bool many: Whether to deserialize `obj` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to ignore missing fields. If `None`,\n            the value for `self.partial` is used. If its value is an iterable,\n            only missing fields listed in that iterable will be ignored.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `UnmarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        # TODO: This avoids breaking backward compatibility if people were\n        # passing in positional args after `many` for use by `json.loads`, but\n        # ideally we shouldn't have to do this.\n        partial = kwargs.pop('partial', None)\n\n        data = self.opts.json_module.loads(json_data, *args, **kwargs)\n        return self.load(data, many=many, partial=partial)\n\n    def validate(self, data, many=None, partial=None):\n        \"\"\"Validate `data` against the schema, returning a dictionary of\n        validation errors.\n\n        :param dict data: The data to validate.\n        :param bool many: Whether to validate `data` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to ignore missing fields. If `None`,\n            the value for `self.partial` is used. If its value is an iterable,\n            only missing fields listed in that iterable will be ignored.\n        :return: A dictionary of validation errors.\n        :rtype: dict\n\n        .. versionadded:: 1.1.0\n        \"\"\"\n        _, errors = self._do_load(data, many, partial=partial, postprocess=False)\n        return errors\n\n    ##### Private Helpers #####\n\n    def _do_load(self, data, many=None, partial=None, postprocess=True):\n        \"\"\"Deserialize `data`, returning the deserialized result and a dictonary of\n        validation errors.\n\n        :param data: The data to deserialize.\n        :param bool many: Whether to deserialize `data` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to validate required fields. If its value is an iterable,\n            only fields listed in that iterable will be ignored will be allowed missing.\n            If `True`, all fields will be allowed missing.\n            If `None`, the value for `self.partial` is used.\n        :param bool postprocess: Whether to run post_load methods..\n        :return: A tuple of the form (`data`, `errors`)\n        \"\"\"\n        # Callable unmarshalling object\n        unmarshal = marshalling.Unmarshaller()\n        errors = {}\n        many = self.many if many is None else bool(many)\n        if partial is None:\n            partial = self.partial\n        try:\n            processed_data = self._invoke_load_processors(\n                PRE_LOAD,\n                data,\n                many,\n                original_data=data)\n        except ValidationError as err:\n            errors = err.normalized_messages()\n            result = None\n        if not errors:\n            try:\n                result = unmarshal(\n                    processed_data,\n                    self.fields,\n                    many=many,\n                    partial=partial,\n                    dict_class=self.dict_class,\n                    index_errors=self.opts.index_errors,\n                )\n            except ValidationError as error:\n                result = error.data\n            self._invoke_field_validators(unmarshal, data=result, many=many)\n            errors = unmarshal.errors\n            field_errors = bool(errors)\n            # Run schema-level migration\n            try:\n                self._invoke_validators(unmarshal, pass_many=True, data=result, original_data=data,\n                                        many=many, field_errors=field_errors)\n            except ValidationError as err:\n                errors.update(err.messages)\n            try:\n                self._invoke_validators(unmarshal, pass_many=False, data=result, original_data=data,\n                                        many=many, field_errors=field_errors)\n            except ValidationError as err:\n                errors.update(err.messages)\n        # Run post processors\n        if not errors and postprocess:\n            try:\n                result = self._invoke_load_processors(\n                    POST_LOAD,\n                    result,\n                    many,\n                    original_data=data)\n            except ValidationError as err:\n                errors = err.normalized_messages()\n        if errors:\n            # TODO: Remove self.__error_handler__ in a later release\n            if self.__error_handler__ and callable(self.__error_handler__):\n                self.__error_handler__(errors, data)\n            exc = ValidationError(\n                errors,\n                field_names=unmarshal.error_field_names,\n                fields=unmarshal.error_fields,\n                data=data,\n                **unmarshal.error_kwargs\n            )\n            self.handle_error(exc, data)\n            if self.strict:\n                raise exc\n\n        return result, errors\n\n    def _normalize_nested_options(self):\n        \"\"\"Apply then flatten nested schema options\"\"\"\n        if self.only is not None:\n            # Apply the only option to nested fields.\n            self.__apply_nested_option('only', self.only, 'intersection')\n            # Remove the child field names from the only option.\n            self.only = self.set_class(\n                [field.split('.', 1)[0] for field in self.only],\n            )\n        if self.exclude:\n            # Apply the exclude option to nested fields.\n            self.__apply_nested_option('exclude', self.exclude, 'union')\n            # Remove the parent field names from the exclude option.\n            self.exclude = self.set_class(\n                [field for field in self.exclude if '.' not in field],\n            )\n\n    def __apply_nested_option(self, option_name, field_names, set_operation):\n        \"\"\"Apply nested options to nested fields\"\"\"\n        # Split nested field names on the first dot.\n        nested_fields = [name.split('.', 1) for name in field_names if '.' in name]\n        # Partition the nested field names by parent field.\n        nested_options = defaultdict(list)\n        for parent, nested_names in nested_fields:\n            nested_options[parent].append(nested_names)\n        # Apply the nested field options.\n        for key, options in iter(nested_options.items()):\n            new_options = self.set_class(options)\n            original_options = getattr(self.declared_fields[key], option_name, ())\n            if original_options:\n                if set_operation == 'union':\n                    new_options |= self.set_class(original_options)\n                if set_operation == 'intersection':\n                    new_options &= self.set_class(original_options)\n            setattr(self.declared_fields[key], option_name, new_options)\n\n    def _update_fields(self, obj=None, many=False):\n        \"\"\"Update fields based on the passed in object.\"\"\"\n        if self.only is not None:\n            # Return only fields specified in only option\n            if self.opts.fields:\n                field_names = self.set_class(self.opts.fields) & self.set_class(self.only)\n            else:\n                field_names = self.set_class(self.only)\n        elif self.opts.fields:\n            # Return fields specified in fields option\n            field_names = self.set_class(self.opts.fields)\n        elif self.opts.additional:\n            # Return declared fields + additional fields\n            field_names = (self.set_class(self.declared_fields.keys()) |\n                            self.set_class(self.opts.additional))\n        else:\n            field_names = self.set_class(self.declared_fields.keys())\n\n        # If \"exclude\" option or param is specified, remove those fields\n        field_names -= self.exclude\n        ret = self.__filter_fields(field_names, obj, many=many)\n        # Set parents\n        self.__set_field_attrs(ret)\n        self.fields = ret\n        return self.fields\n\n    def on_bind_field(self, field_name, field_obj):\n        \"\"\"Hook to modify a field when it is bound to the `Schema`. No-op by default.\"\"\"\n        return None\n\n    def __set_field_attrs(self, fields_dict):\n        \"\"\"Bind fields to the schema, setting any necessary attributes\n        on the fields (e.g. parent and name).\n\n        Also set field load_only and dump_only values if field_name was\n        specified in ``class Meta``.\n        \"\"\"\n        for field_name, field_obj in iteritems(fields_dict):\n            try:\n                if field_name in self.load_only:\n                    field_obj.load_only = True\n                if field_name in self.dump_only:\n                    field_obj.dump_only = True\n                field_obj._add_to_schema(field_name, self)\n                self.on_bind_field(field_name, field_obj)\n            except TypeError:\n                # field declared as a class, not an instance\n                if (isinstance(field_obj, type) and\n                        issubclass(field_obj, base.FieldABC)):\n                    msg = ('Field for \"{0}\" must be declared as a '\n                           'Field instance, not a class. '\n                           'Did you mean \"fields.{1}()\"?'\n                           .format(field_name, field_obj.__name__))\n                    raise TypeError(msg)\n        return fields_dict\n\n    def __filter_fields(self, field_names, obj, many=False):\n        \"\"\"Return only those field_name:field_obj pairs specified by\n        ``field_names``.\n\n        :param set field_names: Field names to include in the final\n            return dictionary.\n        :param object|Mapping|list obj The object to base filtered fields on.\n        :returns: An dict of field_name:field_obj pairs.\n        \"\"\"\n        if obj and many:\n            try:  # list\n                obj = obj[0]\n            except IndexError:  # Nothing to serialize\n                return dict((k, v) for k, v in self.declared_fields.items() if k in field_names)\n        ret = self.dict_class()\n        for key in field_names:\n            if key in self.declared_fields:\n                ret[key] = self.declared_fields[key]\n            else:  # Implicit field creation (class Meta 'fields' or 'additional')\n                if obj:\n                    attribute_type = None\n                    try:\n                        if isinstance(obj, Mapping):\n                            attribute_type = type(obj[key])\n                        else:\n                            attribute_type = type(getattr(obj, key))\n                    except (AttributeError, KeyError) as err:\n                        err_type = type(err)\n                        raise err_type(\n                            '\"{0}\" is not a valid field for {1}.'.format(key, obj))\n                    field_obj = self.TYPE_MAPPING.get(attribute_type, fields.Field)()\n                else:  # Object is None\n                    field_obj = fields.Field()\n                # map key -> field (default to Raw)\n                ret[key] = field_obj\n        return ret\n\n    def _invoke_dump_processors(self, tag_name, data, many, original_data=None):\n        # The pass_many post-dump processors may do things like add an envelope, so\n        # invoke those after invoking the non-pass_many processors which will expect\n        # to get a list of items.\n        data = self._invoke_processors(tag_name, pass_many=False,\n            data=data, many=many, original_data=original_data)\n        data = self._invoke_processors(tag_name, pass_many=True,\n            data=data, many=many, original_data=original_data)\n        return data\n\n    def _invoke_load_processors(self, tag_name, data, many, original_data=None):\n        # This has to invert the order of the dump processors, so run the pass_many\n        # processors first.\n        data = self._invoke_processors(tag_name, pass_many=True,\n            data=data, many=many, original_data=original_data)\n        data = self._invoke_processors(tag_name, pass_many=False,\n            data=data, many=many, original_data=original_data)\n        return data\n\n    def _invoke_field_validators(self, unmarshal, data, many):\n        for attr_name in self.__processors__[(VALIDATES, False)]:\n            validator = getattr(self, attr_name)\n            validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATES, False)]\n            field_name = validator_kwargs['field_name']\n\n            try:\n                field_obj = self.fields[field_name]\n            except KeyError:\n                if field_name in self.declared_fields:\n                    continue\n                raise ValueError('\"{0}\" field does not exist.'.format(field_name))\n\n            if many:\n                for idx, item in enumerate(data):\n                    try:\n                        value = item[field_obj.attribute or field_name]\n                    except KeyError:\n                        pass\n                    else:\n                        validated_value = unmarshal.call_and_store(\n                            getter_func=validator,\n                            data=value,\n                            field_name=field_obj.load_from or field_name,\n                            field_obj=field_obj,\n                            index=(idx if self.opts.index_errors else None)\n                        )\n                        if validated_value is missing:\n                            data[idx].pop(field_name, None)\n            else:\n                try:\n                    value = data[field_obj.attribute or field_name]\n                except KeyError:\n                    pass\n                else:\n                    validated_value = unmarshal.call_and_store(\n                        getter_func=validator,\n                        data=value,\n                        field_name=field_obj.load_from or field_name,\n                        field_obj=field_obj\n                    )\n                    if validated_value is missing:\n                        data.pop(field_name, None)\n\n    def _invoke_validators(\n            self, unmarshal, pass_many, data, original_data, many, field_errors=False):\n        errors = {}\n        for attr_name in self.__processors__[(VALIDATES_SCHEMA, pass_many)]:\n            validator = getattr(self, attr_name)\n            validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATES_SCHEMA, pass_many)]\n            pass_original = validator_kwargs.get('pass_original', False)\n\n            skip_on_field_errors = validator_kwargs['skip_on_field_errors']\n            if skip_on_field_errors and field_errors:\n                continue\n\n            if pass_many:\n                validator = functools.partial(validator, many=many)\n            if many and not pass_many:\n                for idx, item in enumerate(data):\n                    try:\n                        unmarshal.run_validator(validator,\n                                                item, original_data, self.fields, many=many,\n                                                index=idx, pass_original=pass_original)\n                    except ValidationError as err:\n                        errors.update(err.messages)\n            else:\n                try:\n                    unmarshal.run_validator(validator,\n                                            data, original_data, self.fields, many=many,\n                                            pass_original=pass_original)\n                except ValidationError as err:\n                    errors.update(err.messages)\n        if errors:\n            raise ValidationError(errors)\n        return None\n\n    def _invoke_processors(self, tag_name, pass_many, data, many, original_data=None):\n        for attr_name in self.__processors__[(tag_name, pass_many)]:\n            # This will be a bound method.\n            processor = getattr(self, attr_name)\n\n            processor_kwargs = processor.__marshmallow_kwargs__[(tag_name, pass_many)]\n            pass_original = processor_kwargs.get('pass_original', False)\n\n            if pass_many:\n                if pass_original:\n                    data = utils.if_none(processor(data, many, original_data), data)\n                else:\n                    data = utils.if_none(processor(data, many), data)\n            elif many:\n                if pass_original:\n                    data = [utils.if_none(processor(item, original_data), item)\n                            for item in data]\n                else:\n                    data = [utils.if_none(processor(item), item) for item in data]\n            else:\n                if pass_original:\n                    data = utils.if_none(processor(data, original_data), data)\n                else:\n                    data = utils.if_none(processor(data), data)\n        return data\n\n\nclass Schema(with_metaclass(SchemaMeta, BaseSchema)):\n    __doc__ = BaseSchema.__doc__\n","new_file_content":"# -*- coding: utf-8 -*-\n\"\"\"The :class:`Schema` class, including its metaclass and options (class Meta).\"\"\"\nfrom __future__ import absolute_import, unicode_literals\n\nfrom collections import defaultdict, namedtuple\nimport copy\nimport datetime as dt\nimport decimal\nimport inspect\nimport json\nimport uuid\nimport warnings\nimport functools\n\nfrom marshmallow import base, fields, utils, class_registry, marshalling\nfrom marshmallow.compat import (with_metaclass, iteritems, text_type,\n                                binary_type, Mapping, OrderedDict)\nfrom marshmallow.exceptions import ValidationError\nfrom marshmallow.orderedset import OrderedSet\nfrom marshmallow.decorators import (PRE_DUMP, POST_DUMP, PRE_LOAD, POST_LOAD,\n                                    VALIDATES, VALIDATES_SCHEMA)\nfrom marshmallow.utils import missing\nfrom marshmallow.warnings import RemovedInMarshmallow3Warning, ChangedInMarshmallow3Warning\n\n\n#: Return type of :meth:`Schema.dump` including serialized data and errors\nMarshalResult = namedtuple('MarshalResult', ['data', 'errors'])\n#: Return type of :meth:`Schema.load`, including deserialized data and errors\nUnmarshalResult = namedtuple('UnmarshalResult', ['data', 'errors'])\n\ndef _get_fields(attrs, field_class, pop=False, ordered=False):\n    \"\"\"Get fields from a class. If ordered=True, fields will sorted by creation index.\n\n    :param attrs: Mapping of class attributes\n    :param type field_class: Base field class\n    :param bool pop: Remove matching fields\n    \"\"\"\n    getter = getattr(attrs, 'pop' if pop else 'get')\n    fields = [\n        (field_name, getter(field_name))\n        for field_name, field_value in list(iteritems(attrs))\n        if utils.is_instance_or_subclass(field_value, field_class)\n    ]\n    if ordered:\n        return sorted(\n            fields,\n            key=lambda pair: pair[1]._creation_index,\n        )\n    else:\n        return fields\n\n# This function allows Schemas to inherit from non-Schema classes and ensures\n#   inheritance according to the MRO\ndef _get_fields_by_mro(klass, field_class, ordered=False):\n    \"\"\"Collect fields from a class, following its method resolution order. The\n    class itself is excluded from the search; only its parents are checked. Get\n    fields from ``_declared_fields`` if available, else use ``__dict__``.\n\n    :param type klass: Class whose fields to retrieve\n    :param type field_class: Base field class\n    \"\"\"\n    mro = inspect.getmro(klass)\n    # Loop over mro in reverse to maintain correct order of fields\n    return sum(\n        (\n            _get_fields(\n                getattr(base, '_declared_fields', base.__dict__),\n                field_class,\n                ordered=ordered\n            )\n            for base in mro[:0:-1]\n        ),\n        [],\n    )\n\n\nclass SchemaMeta(type):\n    \"\"\"Metaclass for the Schema class. Binds the declared fields to\n    a ``_declared_fields`` attribute, which is a dictionary mapping attribute\n    names to field objects. Also sets the ``opts`` class attribute, which is\n    the Schema class's ``class Meta`` options.\n    \"\"\"\n\n    def __new__(mcs, name, bases, attrs):\n        meta = attrs.get('Meta')\n        ordered = getattr(meta, 'ordered', False)\n        if not ordered:\n            # Inherit 'ordered' option\n            # Warning: We loop through bases instead of MRO because we don't\n            # yet have access to the class object\n            # (i.e. can't call super before we have fields)\n            for base_ in bases:\n                if hasattr(base_, 'Meta') and hasattr(base_.Meta, 'ordered'):\n                    ordered = base_.Meta.ordered\n                    break\n            else:\n                ordered = False\n        cls_fields = _get_fields(attrs, base.FieldABC, pop=True, ordered=ordered)\n        klass = super(SchemaMeta, mcs).__new__(mcs, name, bases, attrs)\n        inherited_fields = _get_fields_by_mro(klass, base.FieldABC, ordered=ordered)\n\n        # Use getattr rather than attrs['Meta'] so that we get inheritance for free\n        meta = getattr(klass, 'Meta')\n        # Set klass.opts in __new__ rather than __init__ so that it is accessible in\n        # get_declared_fields\n        klass.opts = klass.OPTIONS_CLASS(meta)\n        # Pass the inherited `ordered` into opts\n        klass.opts.ordered = ordered\n        # Add fields specifid in the `include` class Meta option\n        cls_fields += list(klass.opts.include.items())\n\n        dict_cls = OrderedDict if ordered else dict\n        # Assign _declared_fields on class\n        klass._declared_fields = mcs.get_declared_fields(\n            klass=klass,\n            cls_fields=cls_fields,\n            inherited_fields=inherited_fields,\n            dict_cls=dict_cls\n        )\n        return klass\n\n    @classmethod\n    def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls):\n        \"\"\"Returns a dictionary of field_name => `Field` pairs declard on the class.\n        This is exposed mainly so that plugins can add additional fields, e.g. fields\n        computed from class Meta options.\n\n        :param type klass: The class object.\n        :param dict cls_fields: The fields declared on the class, including those added\n            by the ``include`` class Meta option.\n        :param dict inherited_fileds: Inherited fields.\n        :param type dict_class: Either `dict` or `OrderedDict`, depending on the whether\n            the user specified `ordered=True`.\n        \"\"\"\n        return dict_cls(inherited_fields + cls_fields)\n\n    # NOTE: self is the class object\n    def __init__(self, name, bases, attrs):\n        super(SchemaMeta, self).__init__(name, bases, attrs)\n        if name:\n            class_registry.register(name, self)\n        self._resolve_processors()\n\n    def _resolve_processors(self):\n        \"\"\"Add in the decorated processors\n\n        By doing this after constructing the class, we let standard inheritance\n        do all the hard work.\n        \"\"\"\n        mro = inspect.getmro(self)\n        self._has_processors = False\n        self.__processors__ = defaultdict(list)\n        for attr_name in dir(self):\n            # Need to look up the actual descriptor, not whatever might be\n            # bound to the class. This needs to come from the __dict__ of the\n            # declaring class.\n            for parent in mro:\n                try:\n                    attr = parent.__dict__[attr_name]\n                except KeyError:\n                    continue\n                else:\n                    break\n            else:\n                # In case we didn't find the attribute and didn't break above.\n                # We should never hit this - it's just here for completeness\n                # to exclude the possibility of attr being undefined.\n                continue\n\n            try:\n                processor_tags = attr.__marshmallow_tags__\n            except AttributeError:\n                continue\n\n            self._has_processors = bool(processor_tags)\n            for tag in processor_tags:\n                # Use name here so we can get the bound method later, in case\n                # the processor was a descriptor or something.\n                self.__processors__[tag].append(attr_name)\n\n\nclass SchemaOpts(object):\n    \"\"\"class Meta options for the :class:`Schema`. Defines defaults.\"\"\"\n\n    def __init__(self, meta):\n        self.fields = getattr(meta, 'fields', ())\n        if not isinstance(self.fields, (list, tuple)):\n            raise ValueError(\"`fields` option must be a list or tuple.\")\n        self.additional = getattr(meta, 'additional', ())\n        if not isinstance(self.additional, (list, tuple)):\n            raise ValueError(\"`additional` option must be a list or tuple.\")\n        if self.fields and self.additional:\n            raise ValueError(\"Cannot set both `fields` and `additional` options\"\n                            \" for the same Schema.\")\n        self.exclude = getattr(meta, 'exclude', ())\n        if not isinstance(self.exclude, (list, tuple)):\n            raise ValueError(\"`exclude` must be a list or tuple.\")\n        self.strict = getattr(meta, 'strict', False)\n        if hasattr(meta, 'dateformat'):\n            warnings.warn(\n                \"The dateformat option is renamed to datetimeformat in marshmallow 3.\",\n                ChangedInMarshmallow3Warning\n            )\n        self.dateformat = getattr(meta, 'dateformat', None)\n        if hasattr(meta, 'json_module'):\n            warnings.warn(\n                \"The json_module option is renamed to render_module in marshmallow 3.\",\n                ChangedInMarshmallow3Warning\n            )\n        self.json_module = getattr(meta, 'json_module', json)\n        if hasattr(meta, 'skip_missing'):\n            warnings.warn(\n                'The skip_missing option is no longer necessary. Missing inputs passed to '\n                'Schema.dump will be excluded from the serialized output by default.',\n                UserWarning\n            )\n        self.ordered = getattr(meta, 'ordered', False)\n        self.index_errors = getattr(meta, 'index_errors', True)\n        self.include = getattr(meta, 'include', {})\n        self.load_only = getattr(meta, 'load_only', ())\n        self.dump_only = getattr(meta, 'dump_only', ())\n\n\nclass BaseSchema(base.SchemaABC):\n    \"\"\"Base schema class with which to define custom schemas.\n\n    Example usage:\n\n    .. code-block:: python\n\n        import datetime as dt\n        from marshmallow import Schema, fields\n\n        class Album(object):\n            def __init__(self, title, release_date):\n                self.title = title\n                self.release_date = release_date\n\n        class AlbumSchema(Schema):\n            title = fields.Str()\n            release_date = fields.Date()\n\n        # Or, equivalently\n        class AlbumSchema2(Schema):\n            class Meta:\n                fields = (\"title\", \"release_date\")\n\n        album = Album(\"Beggars Banquet\", dt.date(1968, 12, 6))\n        schema = AlbumSchema()\n        data, errors = schema.dump(album)\n        data  # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'}\n\n    :param dict extra: A dict of extra attributes to bind to the serialized result.\n    :param tuple|list only: Whitelist of fields to select when instantiating the Schema.\n        If None, all fields are used.\n        Nested fields can be represented with dot delimiters.\n    :param tuple|list exclude: Blacklist of fields to exclude when instantiating the Schema.\n        If a field appears in both `only` and `exclude`, it is not used.\n        Nested fields can be represented with dot delimiters.\n    :param str prefix: Optional prefix that will be prepended to all the\n        serialized field names.\n    :param bool strict: If `True`, raise errors if invalid data are passed in\n        instead of failing silently and storing the errors.\n    :param bool many: Should be set to `True` if ``obj`` is a collection\n        so that the object will be serialized to a list.\n    :param dict context: Optional context passed to :class:`fields.Method` and\n        :class:`fields.Function` fields.\n    :param tuple|list load_only: Fields to skip during serialization (write-only fields)\n    :param tuple|list dump_only: Fields to skip during deserialization (read-only fields)\n    :param bool|tuple partial: Whether to ignore missing fields. If its value\n        is an iterable, only missing fields listed in that iterable will be\n        ignored.\n\n    .. versionchanged:: 2.0.0\n        `__validators__`, `__preprocessors__`, and `__data_handlers__` are removed in favor of\n        `marshmallow.decorators.validates_schema`,\n        `marshmallow.decorators.pre_load` and `marshmallow.decorators.post_dump`.\n        `__accessor__` and `__error_handler__` are deprecated. Implement the\n        `handle_error` and `get_attribute` methods instead.\n        \"\"\"\n    TYPE_MAPPING = {\n        text_type: fields.String,\n        binary_type: fields.String,\n        dt.datetime: fields.DateTime,\n        float: fields.Float,\n        bool: fields.Boolean,\n        tuple: fields.Raw,\n        list: fields.Raw,\n        set: fields.Raw,\n        int: fields.Integer,\n        uuid.UUID: fields.UUID,\n        dt.time: fields.Time,\n        dt.date: fields.Date,\n        dt.timedelta: fields.TimeDelta,\n        decimal.Decimal: fields.Decimal,\n    }\n\n    OPTIONS_CLASS = SchemaOpts\n\n    #: DEPRECATED: Custom error handler function. May be `None`.\n    __error_handler__ = None\n    #: DEPRECATED: Function used to get values of an object.\n    __accessor__ = None\n\n    class Meta(object):\n        \"\"\"Options object for a Schema.\n\n        Example usage: ::\n\n            class Meta:\n                fields = (\"id\", \"email\", \"date_created\")\n                exclude = (\"password\", \"secret_attribute\")\n\n        Available options:\n\n        - ``fields``: Tuple or list of fields to include in the serialized result.\n        - ``additional``: Tuple or list of fields to include *in addition* to the\n            explicitly declared fields. ``additional`` and ``fields`` are\n            mutually-exclusive options.\n        - ``include``: Dictionary of additional fields to include in the schema. It is\n            usually better to define fields as class variables, but you may need to\n            use this option, e.g., if your fields are Python keywords. May be an\n            `OrderedDict`.\n        - ``exclude``: Tuple or list of fields to exclude in the serialized result.\n            Nested fields can be represented with dot delimiters.\n        - ``dateformat``: Date format for all DateTime fields that do not have their\n            date format explicitly specified.\n        - ``strict``: If `True`, raise errors during marshalling rather than\n            storing them.\n        - ``json_module``: JSON module to use for `loads` and `dumps`.\n            Defaults to the ``json`` module in the stdlib.\n        - ``ordered``: If `True`, order serialization output according to the\n            order in which fields were declared. Output of `Schema.dump` will be a\n            `collections.OrderedDict`.\n        - ``index_errors``: If `True`, errors dictionaries will include the index\n            of invalid items in a collection.\n        - ``load_only``: Tuple or list of fields to exclude from serialized results.\n        - ``dump_only``: Tuple or list of fields to exclude from deserialization\n        \"\"\"\n        pass\n\n    def __init__(self, extra=None, only=None, exclude=(), prefix='', strict=None,\n                 many=False, context=None, load_only=(), dump_only=(),\n                 partial=False):\n        # copy declared fields from metaclass\n        self.declared_fields = copy.deepcopy(self._declared_fields)\n        self.many = many\n        self.only = only\n        self.exclude = set(self.opts.exclude) | set(exclude)\n        if prefix:\n            warnings.warn(\n                'The `prefix` argument is deprecated. Use a post_dump '\n                'method to insert a prefix instead.',\n                RemovedInMarshmallow3Warning\n            )\n        self.prefix = prefix\n        self.strict = strict if strict is not None else self.opts.strict\n        self.ordered = self.opts.ordered\n        self.load_only = set(load_only) or set(self.opts.load_only)\n        self.dump_only = set(dump_only) or set(self.opts.dump_only)\n        self.partial = partial\n        #: Dictionary mapping field_names -> :class:`Field` objects\n        self.fields = self.dict_class()\n        if extra:\n            warnings.warn(\n                'The `extra` argument is deprecated. Use a post_dump '\n                'method to add additional data instead.',\n                RemovedInMarshmallow3Warning\n            )\n        self.extra = extra\n        self.context = context or {}\n        self._normalize_nested_options()\n        self._types_seen = set()\n        self._update_fields(many=many)\n\n    def __repr__(self):\n        return '<{ClassName}(many={self.many}, strict={self.strict})>'.format(\n            ClassName=self.__class__.__name__, self=self\n        )\n\n    def _postprocess(self, data, many, obj):\n        if self.extra:\n            if many:\n                for each in data:\n                    each.update(self.extra)\n            else:\n                data.update(self.extra)\n        return data\n\n    @property\n    def dict_class(self):\n        return OrderedDict if self.ordered else dict\n\n    @property\n    def set_class(self):\n        return OrderedSet if self.ordered else set\n\n    ##### Override-able methods #####\n\n    def handle_error(self, error, data):\n        \"\"\"Custom error handler function for the schema.\n\n        :param ValidationError error: The `ValidationError` raised during (de)serialization.\n        :param data: The original input data.\n\n        .. versionadded:: 2.0.0\n        \"\"\"\n        pass\n\n    def get_attribute(self, attr, obj, default):\n        \"\"\"Defines how to pull values from an object to serialize.\n\n        .. versionadded:: 2.0.0\n        \"\"\"\n        return utils.get_value(attr, obj, default)\n\n    ##### Handler decorators (deprecated) #####\n\n    @classmethod\n    def error_handler(cls, func):\n        \"\"\"Decorator that registers an error handler function for the schema.\n        The function receives the :class:`Schema` instance, a dictionary of errors,\n        and the serialized object (if serializing data) or data dictionary (if\n        deserializing data) as arguments.\n\n        Example: ::\n\n            class UserSchema(Schema):\n                email = fields.Email()\n\n            @UserSchema.error_handler\n            def handle_errors(schema, errors, obj):\n                raise ValueError('An error occurred while marshalling {}'.format(obj))\n\n            user = User(email='invalid')\n            UserSchema().dump(user)  # => raises ValueError\n            UserSchema().load({'email': 'bademail'})  # raises ValueError\n\n        .. versionadded:: 0.7.0\n        .. deprecated:: 2.0.0\n            Set the ``error_handler`` class Meta option instead.\n        \"\"\"\n        warnings.warn(\n            'Schema.error_handler is deprecated. Set the error_handler class Meta option '\n            'instead.', category=DeprecationWarning\n        )\n        cls.__error_handler__ = func\n        return func\n\n    @classmethod\n    def accessor(cls, func):\n        \"\"\"Decorator that registers a function for pulling values from an object\n        to serialize. The function receives the :class:`Schema` instance, the\n        ``key`` of the value to get, the ``obj`` to serialize, and an optional\n        ``default`` value.\n\n        .. deprecated:: 2.0.0\n            Set the ``error_handler`` class Meta option instead.\n        \"\"\"\n        warnings.warn(\n            'Schema.accessor is deprecated. Set the accessor class Meta option '\n            'instead.', category=DeprecationWarning\n        )\n        cls.__accessor__ = func\n        return func\n\n    ##### Serialization/Deserialization API #####\n\n    def dump(self, obj, many=None, update_fields=True, **kwargs):\n        \"\"\"Serialize an object to native Python data types according to this\n        Schema's fields.\n\n        :param obj: The object to serialize.\n        :param bool many: Whether to serialize `obj` as a collection. If `None`, the value\n            for `self.many` is used.\n        :param bool update_fields: Whether to update the schema's field classes. Typically\n            set to `True`, but may be `False` when serializing a homogenous collection.\n            This parameter is used by `fields.Nested` to avoid multiple updates.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `MarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        # Callable marshalling object\n        marshal = marshalling.Marshaller(prefix=self.prefix)\n        errors = {}\n        many = self.many if many is None else bool(many)\n        if many and utils.is_iterable_but_not_string(obj):\n            obj = list(obj)\n\n        if self._has_processors:\n            try:\n                processed_obj = self._invoke_dump_processors(\n                    PRE_DUMP,\n                    obj,\n                    many,\n                    original_data=obj)\n            except ValidationError as error:\n                errors = error.normalized_messages()\n                result = None\n        else:\n            processed_obj = obj\n\n        if not errors:\n            if update_fields:\n                obj_type = type(processed_obj)\n                if obj_type not in self._types_seen:\n                    self._update_fields(processed_obj, many=many)\n                    if not isinstance(processed_obj, Mapping):\n                        self._types_seen.add(obj_type)\n\n            try:\n                preresult = marshal(\n                    processed_obj,\n                    self.fields,\n                    many=many,\n                    # TODO: Remove self.__accessor__ in a later release\n                    accessor=self.get_attribute or self.__accessor__,\n                    dict_class=self.dict_class,\n                    index_errors=self.opts.index_errors,\n                    **kwargs\n                )\n            except ValidationError as error:\n                errors = marshal.errors\n                preresult = error.data\n\n            result = self._postprocess(preresult, many, obj=obj)\n\n        if not errors and self._has_processors:\n            try:\n                result = self._invoke_dump_processors(\n                    POST_DUMP,\n                    result,\n                    many,\n                    original_data=obj)\n            except ValidationError as error:\n                errors = error.normalized_messages()\n        if errors:\n            # TODO: Remove self.__error_handler__ in a later release\n            if self.__error_handler__ and callable(self.__error_handler__):\n                self.__error_handler__(errors, obj)\n            exc = ValidationError(\n                errors,\n                field_names=marshal.error_field_names,\n                fields=marshal.error_fields,\n                data=obj,\n                **marshal.error_kwargs\n            )\n            self.handle_error(exc, obj)\n            if self.strict:\n                raise exc\n\n        return MarshalResult(result, errors)\n\n    def dumps(self, obj, many=None, update_fields=True, *args, **kwargs):\n        \"\"\"Same as :meth:`dump`, except return a JSON-encoded string.\n\n        :param obj: The object to serialize.\n        :param bool many: Whether to serialize `obj` as a collection. If `None`, the value\n            for `self.many` is used.\n        :param bool update_fields: Whether to update the schema's field classes. Typically\n            set to `True`, but may be `False` when serializing a homogenous collection.\n            This parameter is used by `fields.Nested` to avoid multiple updates.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `MarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        deserialized, errors = self.dump(obj, many=many, update_fields=update_fields)\n        ret = self.opts.json_module.dumps(deserialized, *args, **kwargs)\n        return MarshalResult(ret, errors)\n\n    def load(self, data, many=None, partial=None):\n        \"\"\"Deserialize a data structure to an object defined by this Schema's\n        fields and :meth:`make_object`.\n\n        :param dict data: The data to deserialize.\n        :param bool many: Whether to deserialize `data` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to ignore missing fields. If `None`,\n            the value for `self.partial` is used. If its value is an iterable,\n            only missing fields listed in that iterable will be ignored.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `UnmarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        result, errors = self._do_load(data, many, partial=partial, postprocess=True)\n        return UnmarshalResult(data=result, errors=errors)\n\n    def loads(self, json_data, many=None, *args, **kwargs):\n        \"\"\"Same as :meth:`load`, except it takes a JSON string as input.\n\n        :param str json_data: A JSON string of the data to deserialize.\n        :param bool many: Whether to deserialize `obj` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to ignore missing fields. If `None`,\n            the value for `self.partial` is used. If its value is an iterable,\n            only missing fields listed in that iterable will be ignored.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `UnmarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        # TODO: This avoids breaking backward compatibility if people were\n        # passing in positional args after `many` for use by `json.loads`, but\n        # ideally we shouldn't have to do this.\n        partial = kwargs.pop('partial', None)\n\n        data = self.opts.json_module.loads(json_data, *args, **kwargs)\n        return self.load(data, many=many, partial=partial)\n\n    def validate(self, data, many=None, partial=None):\n        \"\"\"Validate `data` against the schema, returning a dictionary of\n        validation errors.\n\n        :param dict data: The data to validate.\n        :param bool many: Whether to validate `data` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to ignore missing fields. If `None`,\n            the value for `self.partial` is used. If its value is an iterable,\n            only missing fields listed in that iterable will be ignored.\n        :return: A dictionary of validation errors.\n        :rtype: dict\n\n        .. versionadded:: 1.1.0\n        \"\"\"\n        _, errors = self._do_load(data, many, partial=partial, postprocess=False)\n        return errors\n\n    ##### Private Helpers #####\n\n    def _do_load(self, data, many=None, partial=None, postprocess=True):\n        \"\"\"Deserialize `data`, returning the deserialized result and a dictonary of\n        validation errors.\n\n        :param data: The data to deserialize.\n        :param bool many: Whether to deserialize `data` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to validate required fields. If its value is an iterable,\n            only fields listed in that iterable will be ignored will be allowed missing.\n            If `True`, all fields will be allowed missing.\n            If `None`, the value for `self.partial` is used.\n        :param bool postprocess: Whether to run post_load methods..\n        :return: A tuple of the form (`data`, `errors`)\n        \"\"\"\n        # Callable unmarshalling object\n        unmarshal = marshalling.Unmarshaller()\n        errors = {}\n        many = self.many if many is None else bool(many)\n        if partial is None:\n            partial = self.partial\n        try:\n            processed_data = self._invoke_load_processors(\n                PRE_LOAD,\n                data,\n                many,\n                original_data=data)\n        except ValidationError as err:\n            errors = err.normalized_messages()\n            result = None\n        if not errors:\n            try:\n                result = unmarshal(\n                    processed_data,\n                    self.fields,\n                    many=many,\n                    partial=partial,\n                    dict_class=self.dict_class,\n                    index_errors=self.opts.index_errors,\n                )\n            except ValidationError as error:\n                result = error.data\n            self._invoke_field_validators(unmarshal, data=result, many=many)\n            errors = unmarshal.errors\n            field_errors = bool(errors)\n            # Run schema-level migration\n            try:\n                self._invoke_validators(unmarshal, pass_many=True, data=result, original_data=data,\n                                        many=many, field_errors=field_errors)\n            except ValidationError as err:\n                errors.update(err.messages)\n            try:\n                self._invoke_validators(unmarshal, pass_many=False, data=result, original_data=data,\n                                        many=many, field_errors=field_errors)\n            except ValidationError as err:\n                errors.update(err.messages)\n        # Run post processors\n        if not errors and postprocess:\n            try:\n                result = self._invoke_load_processors(\n                    POST_LOAD,\n                    result,\n                    many,\n                    original_data=data)\n            except ValidationError as err:\n                errors = err.normalized_messages()\n        if errors:\n            # TODO: Remove self.__error_handler__ in a later release\n            if self.__error_handler__ and callable(self.__error_handler__):\n                self.__error_handler__(errors, data)\n            exc = ValidationError(\n                errors,\n                field_names=unmarshal.error_field_names,\n                fields=unmarshal.error_fields,\n                data=data,\n                **unmarshal.error_kwargs\n            )\n            self.handle_error(exc, data)\n            if self.strict:\n                raise exc\n\n        return result, errors\n\n    def _normalize_nested_options(self):\n        \"\"\"Apply then flatten nested schema options\"\"\"\n        if self.only is not None:\n            # Apply the only option to nested fields.\n            self.__apply_nested_option('only', self.only, 'intersection')\n            # Remove the child field names from the only option.\n            self.only = self.set_class(\n                [field.split('.', 1)[0] for field in self.only],\n            )\n        if self.exclude:\n            # Apply the exclude option to nested fields.\n            self.__apply_nested_option('exclude', self.exclude, 'union')\n            # Remove the parent field names from the exclude option.\n            self.exclude = self.set_class(\n                [field for field in self.exclude if '.' not in field],\n            )\n\n    def __apply_nested_option(self, option_name, field_names, set_operation):\n        \"\"\"Apply nested options to nested fields\"\"\"\n        # Split nested field names on the first dot.\n        nested_fields = [name.split('.', 1) for name in field_names if '.' in name]\n        # Partition the nested field names by parent field.\n        nested_options = defaultdict(list)\n        for parent, nested_names in nested_fields:\n            nested_options[parent].append(nested_names)\n        # Apply the nested field options.\n        for key, options in iter(nested_options.items()):\n            new_options = self.set_class(options)\n            original_options = getattr(self.declared_fields[key], option_name, ())\n            if original_options:\n                if set_operation == 'union':\n                    new_options |= self.set_class(original_options)\n                if set_operation == 'intersection':\n                    new_options &= self.set_class(original_options)\n            setattr(self.declared_fields[key], option_name, new_options)\n\n    def _update_fields(self, obj=None, many=False):\n        \"\"\"Update fields based on the passed in object.\"\"\"\n        if self.only is not None:\n            # Return only fields specified in only option\n            if self.opts.fields:\n                field_names = self.set_class(self.opts.fields) & self.set_class(self.only)\n            else:\n                field_names = self.set_class(self.only)\n        elif self.opts.fields:\n            # Return fields specified in fields option\n            field_names = self.set_class(self.opts.fields)\n        elif self.opts.additional:\n            # Return declared fields + additional fields\n            field_names = (self.set_class(self.declared_fields.keys()) |\n                            self.set_class(self.opts.additional))\n        else:\n            field_names = self.set_class(self.declared_fields.keys())\n\n        # If \"exclude\" option or param is specified, remove those fields\n        field_names -= self.exclude\n        ret = self.__filter_fields(field_names, obj, many=many)\n        # Set parents\n        self.__set_field_attrs(ret)\n        self.fields = ret\n        return self.fields\n\n    def on_bind_field(self, field_name, field_obj):\n        \"\"\"Hook to modify a field when it is bound to the `Schema`. No-op by default.\"\"\"\n        return None\n\n    def __set_field_attrs(self, fields_dict):\n        \"\"\"Bind fields to the schema, setting any necessary attributes\n        on the fields (e.g. parent and name).\n\n        Also set field load_only and dump_only values if field_name was\n        specified in ``class Meta``.\n        \"\"\"\n        for field_name, field_obj in iteritems(fields_dict):\n            try:\n                if field_name in self.load_only:\n                    field_obj.load_only = True\n                if field_name in self.dump_only:\n                    field_obj.dump_only = True\n                field_obj._add_to_schema(field_name, self)\n                self.on_bind_field(field_name, field_obj)\n            except TypeError:\n                # field declared as a class, not an instance\n                if (isinstance(field_obj, type) and\n                        issubclass(field_obj, base.FieldABC)):\n                    msg = ('Field for \"{0}\" must be declared as a '\n                           'Field instance, not a class. '\n                           'Did you mean \"fields.{1}()\"?'\n                           .format(field_name, field_obj.__name__))\n                    raise TypeError(msg)\n        return fields_dict\n\n    def __filter_fields(self, field_names, obj, many=False):\n        \"\"\"Return only those field_name:field_obj pairs specified by\n        ``field_names``.\n\n        :param set field_names: Field names to include in the final\n            return dictionary.\n        :param object|Mapping|list obj The object to base filtered fields on.\n        :returns: An dict of field_name:field_obj pairs.\n        \"\"\"\n        if obj and many:\n            try:  # list\n                obj = obj[0]\n            except IndexError:  # Nothing to serialize\n                return dict((k, v) for k, v in self.declared_fields.items() if k in field_names)\n        ret = self.dict_class()\n        for key in field_names:\n            if key in self.declared_fields:\n                ret[key] = self.declared_fields[key]\n            else:  # Implicit field creation (class Meta 'fields' or 'additional')\n                if obj:\n                    attribute_type = None\n                    try:\n                        if isinstance(obj, Mapping):\n                            attribute_type = type(obj[key])\n                        else:\n                            attribute_type = type(getattr(obj, key))\n                    except (AttributeError, KeyError) as err:\n                        err_type = type(err)\n                        raise err_type(\n                            '\"{0}\" is not a valid field for {1}.'.format(key, obj))\n                    field_obj = self.TYPE_MAPPING.get(attribute_type, fields.Field)()\n                else:  # Object is None\n                    field_obj = fields.Field()\n                # map key -> field (default to Raw)\n                ret[key] = field_obj\n        return ret\n\n    def _invoke_dump_processors(self, tag_name, data, many, original_data=None):\n        # The pass_many post-dump processors may do things like add an envelope, so\n        # invoke those after invoking the non-pass_many processors which will expect\n        # to get a list of items.\n        data = self._invoke_processors(tag_name, pass_many=False,\n            data=data, many=many, original_data=original_data)\n        data = self._invoke_processors(tag_name, pass_many=True,\n            data=data, many=many, original_data=original_data)\n        return data\n\n    def _invoke_load_processors(self, tag_name, data, many, original_data=None):\n        # This has to invert the order of the dump processors, so run the pass_many\n        # processors first.\n        data = self._invoke_processors(tag_name, pass_many=True,\n            data=data, many=many, original_data=original_data)\n        data = self._invoke_processors(tag_name, pass_many=False,\n            data=data, many=many, original_data=original_data)\n        return data\n\n    def _invoke_field_validators(self, unmarshal, data, many):\n        for attr_name in self.__processors__[(VALIDATES, False)]:\n            validator = getattr(self, attr_name)\n            validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATES, False)]\n            field_name = validator_kwargs['field_name']\n\n            try:\n                field_obj = self.fields[field_name]\n            except KeyError:\n                if field_name in self.declared_fields:\n                    continue\n                raise ValueError('\"{0}\" field does not exist.'.format(field_name))\n\n            if many:\n                for idx, item in enumerate(data):\n                    try:\n                        value = item[field_obj.attribute or field_name]\n                    except (KeyError, TypeError):\n                        pass\n                    else:\n                        validated_value = unmarshal.call_and_store(\n                            getter_func=validator,\n                            data=value,\n                            field_name=field_obj.load_from or field_name,\n                            field_obj=field_obj,\n                            index=(idx if self.opts.index_errors else None)\n                        )\n                        if validated_value is missing:\n                            data[idx].pop(field_name, None)\n            else:\n                try:\n                    value = data[field_obj.attribute or field_name]\n                except (KeyError, TypeError):\n                    pass\n                else:\n                    validated_value = unmarshal.call_and_store(\n                        getter_func=validator,\n                        data=value,\n                        field_name=field_obj.load_from or field_name,\n                        field_obj=field_obj\n                    )\n                    if validated_value is missing:\n                        data.pop(field_name, None)\n\n    def _invoke_validators(\n            self, unmarshal, pass_many, data, original_data, many, field_errors=False):\n        errors = {}\n        for attr_name in self.__processors__[(VALIDATES_SCHEMA, pass_many)]:\n            validator = getattr(self, attr_name)\n            validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATES_SCHEMA, pass_many)]\n            pass_original = validator_kwargs.get('pass_original', False)\n\n            skip_on_field_errors = validator_kwargs['skip_on_field_errors']\n            if skip_on_field_errors and field_errors:\n                continue\n\n            if pass_many:\n                validator = functools.partial(validator, many=many)\n            if many and not pass_many:\n                for idx, item in enumerate(data):\n                    try:\n                        unmarshal.run_validator(validator,\n                                                item, original_data, self.fields, many=many,\n                                                index=idx, pass_original=pass_original)\n                    except ValidationError as err:\n                        errors.update(err.messages)\n            else:\n                try:\n                    unmarshal.run_validator(validator,\n                                            data, original_data, self.fields, many=many,\n                                            pass_original=pass_original)\n                except ValidationError as err:\n                    errors.update(err.messages)\n        if errors:\n            raise ValidationError(errors)\n        return None\n\n    def _invoke_processors(self, tag_name, pass_many, data, many, original_data=None):\n        for attr_name in self.__processors__[(tag_name, pass_many)]:\n            # This will be a bound method.\n            processor = getattr(self, attr_name)\n\n            processor_kwargs = processor.__marshmallow_kwargs__[(tag_name, pass_many)]\n            pass_original = processor_kwargs.get('pass_original', False)\n\n            if pass_many:\n                if pass_original:\n                    data = utils.if_none(processor(data, many, original_data), data)\n                else:\n                    data = utils.if_none(processor(data, many), data)\n            elif many:\n                if pass_original:\n                    data = [utils.if_none(processor(item, original_data), item)\n                            for item in data]\n                else:\n                    data = [utils.if_none(processor(item), item) for item in data]\n            else:\n                if pass_original:\n                    data = utils.if_none(processor(data, original_data), data)\n                else:\n                    data = utils.if_none(processor(data), data)\n        return data\n\n\nclass Schema(with_metaclass(SchemaMeta, BaseSchema)):\n    __doc__ = BaseSchema.__doc__\n","header":{"file":{"path":"src/marshmallow/schema.py"},"misc_line":null},"index_line":null,"is_binary_file":false,"binary_line":null,"minus_file":{"path":"a/src/marshmallow/schema.py"},"plus_file":{"path":"b/src/marshmallow/schema.py"},"hunks":[{"descriptor":{"old_range":{"start":877,"length":7},"new_range":{"start":877,"length":7},"section":"def _invoke_field_validators(self, unmarshal, data, many):"},"line_group":{"all_lines":[{"content":"                for idx, item in enumerate(data):","type":"context"},{"content":"                    try:","type":"context"},{"content":"                        value = item[field_obj.attribute or field_name]","type":"context"},{"content":"                    except KeyError:","type":"deleted"},{"content":"                    except (KeyError, TypeError):","type":"added"},{"content":"                        pass","type":"context"},{"content":"                    else:","type":"context"},{"content":"                        validated_value = unmarshal.call_and_store(","type":"context"}]},"modified_entities":[],"added_entities":[],"deleted_entities":[]},{"descriptor":{"old_range":{"start":892,"length":7},"new_range":{"start":892,"length":7},"section":"def _invoke_field_validators(self, unmarshal, data, many):"},"line_group":{"all_lines":[{"content":"            else:","type":"context"},{"content":"                try:","type":"context"},{"content":"                    value = data[field_obj.attribute or field_name]","type":"context"},{"content":"                except KeyError:","type":"deleted"},{"content":"                except (KeyError, TypeError):","type":"added"},{"content":"                    pass","type":"context"},{"content":"                else:","type":"context"},{"content":"                    validated_value = unmarshal.call_and_store(","type":"context"},{"content":"","type":"context"}]},"modified_entities":[],"added_entities":[],"deleted_entities":[]}]}],"old_commit_hash":"2be2d83a1a9a6d3d9b85804f3ab545cecc409bb0","new_commit_hash":"2a46fc8f09458fd268abbf3577ee7666bb204b62","commit_message":"Fix invalid type handling when nested schema uses `@validates`","commit_date":"2019-08-13T00:34:32-04:00","metadata":{}}
problem_statement: [version 2.20.0] TypeError: 'NoneType' object is not subscriptable
  After update from version 2.19.5 to 2.20.0 I got error for code like:
  
  ```python
  from marshmallow import Schema, fields, validates
  
  
  class Bar(Schema):
      value = fields.String()
  
      @validates('value')  # <- issue here
      def validate_value(self, value):
          pass
  
  
  class Foo(Schema):
      bar = fields.Nested(Bar)
  
  
  sch = Foo()
  
  sch.validate({
      'bar': 'invalid',
  })
  ```
  
  ```
  Traceback (most recent call last):
    File "/_/bug_mschema.py", line 19, in <module>
      'bar': 'invalid',
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 628, in validate
      _, errors = self._do_load(data, many, partial=partial, postprocess=False)
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 670, in _do_load
      index_errors=self.opts.index_errors,
    File "/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py", line 292, in deserialize
      index=(index if index_errors else None)
    File "/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py", line 65, in call_and_store
      value = getter_func(data)
    File "/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py", line 285, in <lambda>
      data
    File "/_/env/lib/python3.7/site-packages/marshmallow/fields.py", line 265, in deserialize
      output = self._deserialize(value, attr, data)
    File "/_/env/lib/python3.7/site-packages/marshmallow/fields.py", line 465, in _deserialize
      data, errors = self.schema.load(value)
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 588, in load
      result, errors = self._do_load(data, many, partial=partial, postprocess=True)
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 674, in _do_load
      self._invoke_field_validators(unmarshal, data=result, many=many)
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 894, in _invoke_field_validators
      value = data[field_obj.attribute or field_name]
  TypeError: 'NoneType' object is not subscriptable
  ```
  
patch: diff --git a/src/marshmallow/schema.py b/src/marshmallow/schema.py
  --- a/src/marshmallow/schema.py
  +++ b/src/marshmallow/schema.py
  @@ -877,7 +877,7 @@ def _invoke_field_validators(self, unmarshal, data, many):
                   for idx, item in enumerate(data):
                       try:
                           value = item[field_obj.attribute or field_name]
  -                    except KeyError:
  +                    except (KeyError, TypeError):
                           pass
                       else:
                           validated_value = unmarshal.call_and_store(
  @@ -892,7 +892,7 @@ def _invoke_field_validators(self, unmarshal, data, many):
               else:
                   try:
                       value = data[field_obj.attribute or field_name]
  -                except KeyError:
  +                except (KeyError, TypeError):
                       pass
                   else:
                       validated_value = unmarshal.call_and_store(
   
  
file_context: {"src/marshmallow/schema.py": "# -*- coding: utf-8 -*-\n\"\"\"The :class:`Schema` class, including its metaclass and options (class Meta).\"\"\"\nfrom __future__ import absolute_import, unicode_literals\n\nfrom collections import defaultdict, namedtuple\nimport copy\nimport datetime as dt\nimport decimal\nimport inspect\nimport json\nimport uuid\nimport warnings\nimport functools\n\nfrom marshmallow import base, fields, utils, class_registry, marshalling\nfrom marshmallow.compat import (with_metaclass, iteritems, text_type,\n                                binary_type, Mapping, OrderedDict)\nfrom marshmallow.exceptions import ValidationError\nfrom marshmallow.orderedset import OrderedSet\nfrom marshmallow.decorators import (PRE_DUMP, POST_DUMP, PRE_LOAD, POST_LOAD,\n                                    VALIDATES, VALIDATES_SCHEMA)\nfrom marshmallow.utils import missing\nfrom marshmallow.warnings import RemovedInMarshmallow3Warning, ChangedInMarshmallow3Warning\n\n\n#: Return type of :meth:`Schema.dump` including serialized data and errors\nMarshalResult = namedtuple('MarshalResult', ['data', 'errors'])\n#: Return type of :meth:`Schema.load`, including deserialized data and errors\nUnmarshalResult = namedtuple('UnmarshalResult', ['data', 'errors'])\n\ndef _get_fields(attrs, field_class, pop=False, ordered=False):\n    \"\"\"Get fields from a class. If ordered=True, fields will sorted by creation index.\n\n    :param attrs: Mapping of class attributes\n    :param type field_class: Base field class\n    :param bool pop: Remove matching fields\n    \"\"\"\n    getter = getattr(attrs, 'pop' if pop else 'get')\n    fields = [\n        (field_name, getter(field_name))\n        for field_name, field_value in list(iteritems(attrs))\n        if utils.is_instance_or_subclass(field_value, field_class)\n    ]\n    if ordered:\n        return sorted(\n            fields,\n            key=lambda pair: pair[1]._creation_index,\n        )\n    else:\n        return fields\n\n# This function allows Schemas to inherit from non-Schema classes and ensures\n#   inheritance according to the MRO\ndef _get_fields_by_mro(klass, field_class, ordered=False):\n    \"\"\"Collect fields from a class, following its method resolution order. The\n    class itself is excluded from the search; only its parents are checked. Get\n    fields from ``_declared_fields`` if available, else use ``__dict__``.\n\n    :param type klass: Class whose fields to retrieve\n    :param type field_class: Base field class\n    \"\"\"\n    mro = inspect.getmro(klass)\n    # Loop over mro in reverse to maintain correct order of fields\n    return sum(\n        (\n            _get_fields(\n                getattr(base, '_declared_fields', base.__dict__),\n                field_class,\n                ordered=ordered\n            )\n            for base in mro[:0:-1]\n        ),\n        [],\n    )\n\n\nclass SchemaMeta(type):\n    \"\"\"Metaclass for the Schema class. Binds the declared fields to\n    a ``_declared_fields`` attribute, which is a dictionary mapping attribute\n    names to field objects. Also sets the ``opts`` class attribute, which is\n    the Schema class's ``class Meta`` options.\n    \"\"\"\n\n    def __new__(mcs, name, bases, attrs):\n        meta = attrs.get('Meta')\n        ordered = getattr(meta, 'ordered', False)\n        if not ordered:\n            # Inherit 'ordered' option\n            # Warning: We loop through bases instead of MRO because we don't\n            # yet have access to the class object\n            # (i.e. can't call super before we have fields)\n            for base_ in bases:\n                if hasattr(base_, 'Meta') and hasattr(base_.Meta, 'ordered'):\n                    ordered = base_.Meta.ordered\n                    break\n            else:\n                ordered = False\n        cls_fields = _get_fields(attrs, base.FieldABC, pop=True, ordered=ordered)\n        klass = super(SchemaMeta, mcs).__new__(mcs, name, bases, attrs)\n        inherited_fields = _get_fields_by_mro(klass, base.FieldABC, ordered=ordered)\n\n        # Use getattr rather than attrs['Meta'] so that we get inheritance for free\n        meta = getattr(klass, 'Meta')\n        # Set klass.opts in __new__ rather than __init__ so that it is accessible in\n        # get_declared_fields\n        klass.opts = klass.OPTIONS_CLASS(meta)\n        # Pass the inherited `ordered` into opts\n        klass.opts.ordered = ordered\n        # Add fields specifid in the `include` class Meta option\n        cls_fields += list(klass.opts.include.items())\n\n        dict_cls = OrderedDict if ordered else dict\n        # Assign _declared_fields on class\n        klass._declared_fields = mcs.get_declared_fields(\n            klass=klass,\n            cls_fields=cls_fields,\n            inherited_fields=inherited_fields,\n            dict_cls=dict_cls\n        )\n        return klass\n\n    @classmethod\n    def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls):\n        \"\"\"Returns a dictionary of field_name => `Field` pairs declard on the class.\n        This is exposed mainly so that plugins can add additional fields, e.g. fields\n        computed from class Meta options.\n\n        :param type klass: The class object.\n        :param dict cls_fields: The fields declared on the class, including those added\n            by the ``include`` class Meta option.\n        :param dict inherited_fileds: Inherited fields.\n        :param type dict_class: Either `dict` or `OrderedDict`, depending on the whether\n            the user specified `ordered=True`.\n        \"\"\"\n        return dict_cls(inherited_fields + cls_fields)\n\n    # NOTE: self is the class object\n    def __init__(self, name, bases, attrs):\n        super(SchemaMeta, self).__init__(name, bases, attrs)\n        if name:\n            class_registry.register(name, self)\n        self._resolve_processors()\n\n    def _resolve_processors(self):\n        \"\"\"Add in the decorated processors\n\n        By doing this after constructing the class, we let standard inheritance\n        do all the hard work.\n        \"\"\"\n        mro = inspect.getmro(self)\n        self._has_processors = False\n        self.__processors__ = defaultdict(list)\n        for attr_name in dir(self):\n            # Need to look up the actual descriptor, not whatever might be\n            # bound to the class. This needs to come from the __dict__ of the\n            # declaring class.\n            for parent in mro:\n                try:\n                    attr = parent.__dict__[attr_name]\n                except KeyError:\n                    continue\n                else:\n                    break\n            else:\n                # In case we didn't find the attribute and didn't break above.\n                # We should never hit this - it's just here for completeness\n                # to exclude the possibility of attr being undefined.\n                continue\n\n            try:\n                processor_tags = attr.__marshmallow_tags__\n            except AttributeError:\n                continue\n\n            self._has_processors = bool(processor_tags)\n            for tag in processor_tags:\n                # Use name here so we can get the bound method later, in case\n                # the processor was a descriptor or something.\n                self.__processors__[tag].append(attr_name)\n\n\nclass SchemaOpts(object):\n    \"\"\"class Meta options for the :class:`Schema`. Defines defaults.\"\"\"\n\n    def __init__(self, meta):\n        self.fields = getattr(meta, 'fields', ())\n        if not isinstance(self.fields, (list, tuple)):\n            raise ValueError(\"`fields` option must be a list or tuple.\")\n        self.additional = getattr(meta, 'additional', ())\n        if not isinstance(self.additional, (list, tuple)):\n            raise ValueError(\"`additional` option must be a list or tuple.\")\n        if self.fields and self.additional:\n            raise ValueError(\"Cannot set both `fields` and `additional` options\"\n                            \" for the same Schema.\")\n        self.exclude = getattr(meta, 'exclude', ())\n        if not isinstance(self.exclude, (list, tuple)):\n            raise ValueError(\"`exclude` must be a list or tuple.\")\n        self.strict = getattr(meta, 'strict', False)\n        if hasattr(meta, 'dateformat'):\n            warnings.warn(\n                \"The dateformat option is renamed to datetimeformat in marshmallow 3.\",\n                ChangedInMarshmallow3Warning\n            )\n        self.dateformat = getattr(meta, 'dateformat', None)\n        if hasattr(meta, 'json_module'):\n            warnings.warn(\n                \"The json_module option is renamed to render_module in marshmallow 3.\",\n                ChangedInMarshmallow3Warning\n            )\n        self.json_module = getattr(meta, 'json_module', json)\n        if hasattr(meta, 'skip_missing'):\n            warnings.warn(\n                'The skip_missing option is no longer necessary. Missing inputs passed to '\n                'Schema.dump will be excluded from the serialized output by default.',\n                UserWarning\n            )\n        self.ordered = getattr(meta, 'ordered', False)\n        self.index_errors = getattr(meta, 'index_errors', True)\n        self.include = getattr(meta, 'include', {})\n        self.load_only = getattr(meta, 'load_only', ())\n        self.dump_only = getattr(meta, 'dump_only', ())\n\n\nclass BaseSchema(base.SchemaABC):\n    \"\"\"Base schema class with which to define custom schemas.\n\n    Example usage:\n\n    .. code-block:: python\n\n        import datetime as dt\n        from marshmallow import Schema, fields\n\n        class Album(object):\n            def __init__(self, title, release_date):\n                self.title = title\n                self.release_date = release_date\n\n        class AlbumSchema(Schema):\n            title = fields.Str()\n            release_date = fields.Date()\n\n        # Or, equivalently\n        class AlbumSchema2(Schema):\n            class Meta:\n                fields = (\"title\", \"release_date\")\n\n        album = Album(\"Beggars Banquet\", dt.date(1968, 12, 6))\n        schema = AlbumSchema()\n        data, errors = schema.dump(album)\n        data  # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'}\n\n    :param dict extra: A dict of extra attributes to bind to the serialized result.\n    :param tuple|list only: Whitelist of fields to select when instantiating the Schema.\n        If None, all fields are used.\n        Nested fields can be represented with dot delimiters.\n    :param tuple|list exclude: Blacklist of fields to exclude when instantiating the Schema.\n        If a field appears in both `only` and `exclude`, it is not used.\n        Nested fields can be represented with dot delimiters.\n    :param str prefix: Optional prefix that will be prepended to all the\n        serialized field names.\n    :param bool strict: If `True`, raise errors if invalid data are passed in\n        instead of failing silently and storing the errors.\n    :param bool many: Should be set to `True` if ``obj`` is a collection\n        so that the object will be serialized to a list.\n    :param dict context: Optional context passed to :class:`fields.Method` and\n        :class:`fields.Function` fields.\n    :param tuple|list load_only: Fields to skip during serialization (write-only fields)\n    :param tuple|list dump_only: Fields to skip during deserialization (read-only fields)\n    :param bool|tuple partial: Whether to ignore missing fields. If its value\n        is an iterable, only missing fields listed in that iterable will be\n        ignored.\n\n    .. versionchanged:: 2.0.0\n        `__validators__`, `__preprocessors__`, and `__data_handlers__` are removed in favor of\n        `marshmallow.decorators.validates_schema`,\n        `marshmallow.decorators.pre_load` and `marshmallow.decorators.post_dump`.\n        `__accessor__` and `__error_handler__` are deprecated. Implement the\n        `handle_error` and `get_attribute` methods instead.\n        \"\"\"\n    TYPE_MAPPING = {\n        text_type: fields.String,\n        binary_type: fields.String,\n        dt.datetime: fields.DateTime,\n        float: fields.Float,\n        bool: fields.Boolean,\n        tuple: fields.Raw,\n        list: fields.Raw,\n        set: fields.Raw,\n        int: fields.Integer,\n        uuid.UUID: fields.UUID,\n        dt.time: fields.Time,\n        dt.date: fields.Date,\n        dt.timedelta: fields.TimeDelta,\n        decimal.Decimal: fields.Decimal,\n    }\n\n    OPTIONS_CLASS = SchemaOpts\n\n    #: DEPRECATED: Custom error handler function. May be `None`.\n    __error_handler__ = None\n    #: DEPRECATED: Function used to get values of an object.\n    __accessor__ = None\n\n    class Meta(object):\n        \"\"\"Options object for a Schema.\n\n        Example usage: ::\n\n            class Meta:\n                fields = (\"id\", \"email\", \"date_created\")\n                exclude = (\"password\", \"secret_attribute\")\n\n        Available options:\n\n        - ``fields``: Tuple or list of fields to include in the serialized result.\n        - ``additional``: Tuple or list of fields to include *in addition* to the\n            explicitly declared fields. ``additional`` and ``fields`` are\n            mutually-exclusive options.\n        - ``include``: Dictionary of additional fields to include in the schema. It is\n            usually better to define fields as class variables, but you may need to\n            use this option, e.g., if your fields are Python keywords. May be an\n            `OrderedDict`.\n        - ``exclude``: Tuple or list of fields to exclude in the serialized result.\n            Nested fields can be represented with dot delimiters.\n        - ``dateformat``: Date format for all DateTime fields that do not have their\n            date format explicitly specified.\n        - ``strict``: If `True`, raise errors during marshalling rather than\n            storing them.\n        - ``json_module``: JSON module to use for `loads` and `dumps`.\n            Defaults to the ``json`` module in the stdlib.\n        - ``ordered``: If `True`, order serialization output according to the\n            order in which fields were declared. Output of `Schema.dump` will be a\n            `collections.OrderedDict`.\n        - ``index_errors``: If `True`, errors dictionaries will include the index\n            of invalid items in a collection.\n        - ``load_only``: Tuple or list of fields to exclude from serialized results.\n        - ``dump_only``: Tuple or list of fields to exclude from deserialization\n        \"\"\"\n        pass\n\n    def __init__(self, extra=None, only=None, exclude=(), prefix='', strict=None,\n                 many=False, context=None, load_only=(), dump_only=(),\n                 partial=False):\n        # copy declared fields from metaclass\n        self.declared_fields = copy.deepcopy(self._declared_fields)\n        self.many = many\n        self.only = only\n        self.exclude = set(self.opts.exclude) | set(exclude)\n        if prefix:\n            warnings.warn(\n                'The `prefix` argument is deprecated. Use a post_dump '\n                'method to insert a prefix instead.',\n                RemovedInMarshmallow3Warning\n            )\n        self.prefix = prefix\n        self.strict = strict if strict is not None else self.opts.strict\n        self.ordered = self.opts.ordered\n        self.load_only = set(load_only) or set(self.opts.load_only)\n        self.dump_only = set(dump_only) or set(self.opts.dump_only)\n        self.partial = partial\n        #: Dictionary mapping field_names -> :class:`Field` objects\n        self.fields = self.dict_class()\n        if extra:\n            warnings.warn(\n                'The `extra` argument is deprecated. Use a post_dump '\n                'method to add additional data instead.',\n                RemovedInMarshmallow3Warning\n            )\n        self.extra = extra\n        self.context = context or {}\n        self._normalize_nested_options()\n        self._types_seen = set()\n        self._update_fields(many=many)\n\n    def __repr__(self):\n        return '<{ClassName}(many={self.many}, strict={self.strict})>'.format(\n            ClassName=self.__class__.__name__, self=self\n        )\n\n    def _postprocess(self, data, many, obj):\n        if self.extra:\n            if many:\n                for each in data:\n                    each.update(self.extra)\n            else:\n                data.update(self.extra)\n        return data\n\n    @property\n    def dict_class(self):\n        return OrderedDict if self.ordered else dict\n\n    @property\n    def set_class(self):\n        return OrderedSet if self.ordered else set\n\n    ##### Override-able methods #####\n\n    def handle_error(self, error, data):\n        \"\"\"Custom error handler function for the schema.\n\n        :param ValidationError error: The `ValidationError` raised during (de)serialization.\n        :param data: The original input data.\n\n        .. versionadded:: 2.0.0\n        \"\"\"\n        pass\n\n    def get_attribute(self, attr, obj, default):\n        \"\"\"Defines how to pull values from an object to serialize.\n\n        .. versionadded:: 2.0.0\n        \"\"\"\n        return utils.get_value(attr, obj, default)\n\n    ##### Handler decorators (deprecated) #####\n\n    @classmethod\n    def error_handler(cls, func):\n        \"\"\"Decorator that registers an error handler function for the schema.\n        The function receives the :class:`Schema` instance, a dictionary of errors,\n        and the serialized object (if serializing data) or data dictionary (if\n        deserializing data) as arguments.\n\n        Example: ::\n\n            class UserSchema(Schema):\n                email = fields.Email()\n\n            @UserSchema.error_handler\n            def handle_errors(schema, errors, obj):\n                raise ValueError('An error occurred while marshalling {}'.format(obj))\n\n            user = User(email='invalid')\n            UserSchema().dump(user)  # => raises ValueError\n            UserSchema().load({'email': 'bademail'})  # raises ValueError\n\n        .. versionadded:: 0.7.0\n        .. deprecated:: 2.0.0\n            Set the ``error_handler`` class Meta option instead.\n        \"\"\"\n        warnings.warn(\n            'Schema.error_handler is deprecated. Set the error_handler class Meta option '\n            'instead.', category=DeprecationWarning\n        )\n        cls.__error_handler__ = func\n        return func\n\n    @classmethod\n    def accessor(cls, func):\n        \"\"\"Decorator that registers a function for pulling values from an object\n        to serialize. The function receives the :class:`Schema` instance, the\n        ``key`` of the value to get, the ``obj`` to serialize, and an optional\n        ``default`` value.\n\n        .. deprecated:: 2.0.0\n            Set the ``error_handler`` class Meta option instead.\n        \"\"\"\n        warnings.warn(\n            'Schema.accessor is deprecated. Set the accessor class Meta option '\n            'instead.', category=DeprecationWarning\n        )\n        cls.__accessor__ = func\n        return func\n\n    ##### Serialization/Deserialization API #####\n\n    def dump(self, obj, many=None, update_fields=True, **kwargs):\n        \"\"\"Serialize an object to native Python data types according to this\n        Schema's fields.\n\n        :param obj: The object to serialize.\n        :param bool many: Whether to serialize `obj` as a collection. If `None`, the value\n            for `self.many` is used.\n        :param bool update_fields: Whether to update the schema's field classes. Typically\n            set to `True`, but may be `False` when serializing a homogenous collection.\n            This parameter is used by `fields.Nested` to avoid multiple updates.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `MarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        # Callable marshalling object\n        marshal = marshalling.Marshaller(prefix=self.prefix)\n        errors = {}\n        many = self.many if many is None else bool(many)\n        if many and utils.is_iterable_but_not_string(obj):\n            obj = list(obj)\n\n        if self._has_processors:\n            try:\n                processed_obj = self._invoke_dump_processors(\n                    PRE_DUMP,\n                    obj,\n                    many,\n                    original_data=obj)\n            except ValidationError as error:\n                errors = error.normalized_messages()\n                result = None\n        else:\n            processed_obj = obj\n\n        if not errors:\n            if update_fields:\n                obj_type = type(processed_obj)\n                if obj_type not in self._types_seen:\n                    self._update_fields(processed_obj, many=many)\n                    if not isinstance(processed_obj, Mapping):\n                        self._types_seen.add(obj_type)\n\n            try:\n                preresult = marshal(\n                    processed_obj,\n                    self.fields,\n                    many=many,\n                    # TODO: Remove self.__accessor__ in a later release\n                    accessor=self.get_attribute or self.__accessor__,\n                    dict_class=self.dict_class,\n                    index_errors=self.opts.index_errors,\n                    **kwargs\n                )\n            except ValidationError as error:\n                errors = marshal.errors\n                preresult = error.data\n\n            result = self._postprocess(preresult, many, obj=obj)\n\n        if not errors and self._has_processors:\n            try:\n                result = self._invoke_dump_processors(\n                    POST_DUMP,\n                    result,\n                    many,\n                    original_data=obj)\n            except ValidationError as error:\n                errors = error.normalized_messages()\n        if errors:\n            # TODO: Remove self.__error_handler__ in a later release\n            if self.__error_handler__ and callable(self.__error_handler__):\n                self.__error_handler__(errors, obj)\n            exc = ValidationError(\n                errors,\n                field_names=marshal.error_field_names,\n                fields=marshal.error_fields,\n                data=obj,\n                **marshal.error_kwargs\n            )\n            self.handle_error(exc, obj)\n            if self.strict:\n                raise exc\n\n        return MarshalResult(result, errors)\n\n    def dumps(self, obj, many=None, update_fields=True, *args, **kwargs):\n        \"\"\"Same as :meth:`dump`, except return a JSON-encoded string.\n\n        :param obj: The object to serialize.\n        :param bool many: Whether to serialize `obj` as a collection. If `None`, the value\n            for `self.many` is used.\n        :param bool update_fields: Whether to update the schema's field classes. Typically\n            set to `True`, but may be `False` when serializing a homogenous collection.\n            This parameter is used by `fields.Nested` to avoid multiple updates.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `MarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        deserialized, errors = self.dump(obj, many=many, update_fields=update_fields)\n        ret = self.opts.json_module.dumps(deserialized, *args, **kwargs)\n        return MarshalResult(ret, errors)\n\n    def load(self, data, many=None, partial=None):\n        \"\"\"Deserialize a data structure to an object defined by this Schema's\n        fields and :meth:`make_object`.\n\n        :param dict data: The data to deserialize.\n        :param bool many: Whether to deserialize `data` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to ignore missing fields. If `None`,\n            the value for `self.partial` is used. If its value is an iterable,\n            only missing fields listed in that iterable will be ignored.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `UnmarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        result, errors = self._do_load(data, many, partial=partial, postprocess=True)\n        return UnmarshalResult(data=result, errors=errors)\n\n    def loads(self, json_data, many=None, *args, **kwargs):\n        \"\"\"Same as :meth:`load`, except it takes a JSON string as input.\n\n        :param str json_data: A JSON string of the data to deserialize.\n        :param bool many: Whether to deserialize `obj` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to ignore missing fields. If `None`,\n            the value for `self.partial` is used. If its value is an iterable,\n            only missing fields listed in that iterable will be ignored.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `UnmarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        # TODO: This avoids breaking backward compatibility if people were\n        # passing in positional args after `many` for use by `json.loads`, but\n        # ideally we shouldn't have to do this.\n        partial = kwargs.pop('partial', None)\n\n        data = self.opts.json_module.loads(json_data, *args, **kwargs)\n        return self.load(data, many=many, partial=partial)\n\n    def validate(self, data, many=None, partial=None):\n        \"\"\"Validate `data` against the schema, returning a dictionary of\n        validation errors.\n\n        :param dict data: The data to validate.\n        :param bool many: Whether to validate `data` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to ignore missing fields. If `None`,\n            the value for `self.partial` is used. If its value is an iterable,\n            only missing fields listed in that iterable will be ignored.\n        :return: A dictionary of validation errors.\n        :rtype: dict\n\n        .. versionadded:: 1.1.0\n        \"\"\"\n        _, errors = self._do_load(data, many, partial=partial, postprocess=False)\n        return errors\n\n    ##### Private Helpers #####\n\n    def _do_load(self, data, many=None, partial=None, postprocess=True):\n        \"\"\"Deserialize `data`, returning the deserialized result and a dictonary of\n        validation errors.\n\n        :param data: The data to deserialize.\n        :param bool many: Whether to deserialize `data` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to validate required fields. If its value is an iterable,\n            only fields listed in that iterable will be ignored will be allowed missing.\n            If `True`, all fields will be allowed missing.\n            If `None`, the value for `self.partial` is used.\n        :param bool postprocess: Whether to run post_load methods..\n        :return: A tuple of the form (`data`, `errors`)\n        \"\"\"\n        # Callable unmarshalling object\n        unmarshal = marshalling.Unmarshaller()\n        errors = {}\n        many = self.many if many is None else bool(many)\n        if partial is None:\n            partial = self.partial\n        try:\n            processed_data = self._invoke_load_processors(\n                PRE_LOAD,\n                data,\n                many,\n                original_data=data)\n        except ValidationError as err:\n            errors = err.normalized_messages()\n            result = None\n        if not errors:\n            try:\n                result = unmarshal(\n                    processed_data,\n                    self.fields,\n                    many=many,\n                    partial=partial,\n                    dict_class=self.dict_class,\n                    index_errors=self.opts.index_errors,\n                )\n            except ValidationError as error:\n                result = error.data\n            self._invoke_field_validators(unmarshal, data=result, many=many)\n            errors = unmarshal.errors\n            field_errors = bool(errors)\n            # Run schema-level migration\n            try:\n                self._invoke_validators(unmarshal, pass_many=True, data=result, original_data=data,\n                                        many=many, field_errors=field_errors)\n            except ValidationError as err:\n                errors.update(err.messages)\n            try:\n                self._invoke_validators(unmarshal, pass_many=False, data=result, original_data=data,\n                                        many=many, field_errors=field_errors)\n            except ValidationError as err:\n                errors.update(err.messages)\n        # Run post processors\n        if not errors and postprocess:\n            try:\n                result = self._invoke_load_processors(\n                    POST_LOAD,\n                    result,\n                    many,\n                    original_data=data)\n            except ValidationError as err:\n                errors = err.normalized_messages()\n        if errors:\n            # TODO: Remove self.__error_handler__ in a later release\n            if self.__error_handler__ and callable(self.__error_handler__):\n                self.__error_handler__(errors, data)\n            exc = ValidationError(\n                errors,\n                field_names=unmarshal.error_field_names,\n                fields=unmarshal.error_fields,\n                data=data,\n                **unmarshal.error_kwargs\n            )\n            self.handle_error(exc, data)\n            if self.strict:\n                raise exc\n\n        return result, errors\n\n    def _normalize_nested_options(self):\n        \"\"\"Apply then flatten nested schema options\"\"\"\n        if self.only is not None:\n            # Apply the only option to nested fields.\n            self.__apply_nested_option('only', self.only, 'intersection')\n            # Remove the child field names from the only option.\n            self.only = self.set_class(\n                [field.split('.', 1)[0] for field in self.only],\n            )\n        if self.exclude:\n            # Apply the exclude option to nested fields.\n            self.__apply_nested_option('exclude', self.exclude, 'union')\n            # Remove the parent field names from the exclude option.\n            self.exclude = self.set_class(\n                [field for field in self.exclude if '.' not in field],\n            )\n\n    def __apply_nested_option(self, option_name, field_names, set_operation):\n        \"\"\"Apply nested options to nested fields\"\"\"\n        # Split nested field names on the first dot.\n        nested_fields = [name.split('.', 1) for name in field_names if '.' in name]\n        # Partition the nested field names by parent field.\n        nested_options = defaultdict(list)\n        for parent, nested_names in nested_fields:\n            nested_options[parent].append(nested_names)\n        # Apply the nested field options.\n        for key, options in iter(nested_options.items()):\n            new_options = self.set_class(options)\n            original_options = getattr(self.declared_fields[key], option_name, ())\n            if original_options:\n                if set_operation == 'union':\n                    new_options |= self.set_class(original_options)\n                if set_operation == 'intersection':\n                    new_options &= self.set_class(original_options)\n            setattr(self.declared_fields[key], option_name, new_options)\n\n    def _update_fields(self, obj=None, many=False):\n        \"\"\"Update fields based on the passed in object.\"\"\"\n        if self.only is not None:\n            # Return only fields specified in only option\n            if self.opts.fields:\n                field_names = self.set_class(self.opts.fields) & self.set_class(self.only)\n            else:\n                field_names = self.set_class(self.only)\n        elif self.opts.fields:\n            # Return fields specified in fields option\n            field_names = self.set_class(self.opts.fields)\n        elif self.opts.additional:\n            # Return declared fields + additional fields\n            field_names = (self.set_class(self.declared_fields.keys()) |\n                            self.set_class(self.opts.additional))\n        else:\n            field_names = self.set_class(self.declared_fields.keys())\n\n        # If \"exclude\" option or param is specified, remove those fields\n        field_names -= self.exclude\n        ret = self.__filter_fields(field_names, obj, many=many)\n        # Set parents\n        self.__set_field_attrs(ret)\n        self.fields = ret\n        return self.fields\n\n    def on_bind_field(self, field_name, field_obj):\n        \"\"\"Hook to modify a field when it is bound to the `Schema`. No-op by default.\"\"\"\n        return None\n\n    def __set_field_attrs(self, fields_dict):\n        \"\"\"Bind fields to the schema, setting any necessary attributes\n        on the fields (e.g. parent and name).\n\n        Also set field load_only and dump_only values if field_name was\n        specified in ``class Meta``.\n        \"\"\"\n        for field_name, field_obj in iteritems(fields_dict):\n            try:\n                if field_name in self.load_only:\n                    field_obj.load_only = True\n                if field_name in self.dump_only:\n                    field_obj.dump_only = True\n                field_obj._add_to_schema(field_name, self)\n                self.on_bind_field(field_name, field_obj)\n            except TypeError:\n                # field declared as a class, not an instance\n                if (isinstance(field_obj, type) and\n                        issubclass(field_obj, base.FieldABC)):\n                    msg = ('Field for \"{0}\" must be declared as a '\n                           'Field instance, not a class. '\n                           'Did you mean \"fields.{1}()\"?'\n                           .format(field_name, field_obj.__name__))\n                    raise TypeError(msg)\n        return fields_dict\n\n    def __filter_fields(self, field_names, obj, many=False):\n        \"\"\"Return only those field_name:field_obj pairs specified by\n        ``field_names``.\n\n        :param set field_names: Field names to include in the final\n            return dictionary.\n        :param object|Mapping|list obj The object to base filtered fields on.\n        :returns: An dict of field_name:field_obj pairs.\n        \"\"\"\n        if obj and many:\n            try:  # list\n                obj = obj[0]\n            except IndexError:  # Nothing to serialize\n                return dict((k, v) for k, v in self.declared_fields.items() if k in field_names)\n        ret = self.dict_class()\n        for key in field_names:\n            if key in self.declared_fields:\n                ret[key] = self.declared_fields[key]\n            else:  # Implicit field creation (class Meta 'fields' or 'additional')\n                if obj:\n                    attribute_type = None\n                    try:\n                        if isinstance(obj, Mapping):\n                            attribute_type = type(obj[key])\n                        else:\n                            attribute_type = type(getattr(obj, key))\n                    except (AttributeError, KeyError) as err:\n                        err_type = type(err)\n                        raise err_type(\n                            '\"{0}\" is not a valid field for {1}.'.format(key, obj))\n                    field_obj = self.TYPE_MAPPING.get(attribute_type, fields.Field)()\n                else:  # Object is None\n                    field_obj = fields.Field()\n                # map key -> field (default to Raw)\n                ret[key] = field_obj\n        return ret\n\n    def _invoke_dump_processors(self, tag_name, data, many, original_data=None):\n        # The pass_many post-dump processors may do things like add an envelope, so\n        # invoke those after invoking the non-pass_many processors which will expect\n        # to get a list of items.\n        data = self._invoke_processors(tag_name, pass_many=False,\n            data=data, many=many, original_data=original_data)\n        data = self._invoke_processors(tag_name, pass_many=True,\n            data=data, many=many, original_data=original_data)\n        return data\n\n    def _invoke_load_processors(self, tag_name, data, many, original_data=None):\n        # This has to invert the order of the dump processors, so run the pass_many\n        # processors first.\n        data = self._invoke_processors(tag_name, pass_many=True,\n            data=data, many=many, original_data=original_data)\n        data = self._invoke_processors(tag_name, pass_many=False,\n            data=data, many=many, original_data=original_data)\n        return data\n\n    def _invoke_field_validators(self, unmarshal, data, many):\n        for attr_name in self.__processors__[(VALIDATES, False)]:\n            validator = getattr(self, attr_name)\n            validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATES, False)]\n            field_name = validator_kwargs['field_name']\n\n            try:\n                field_obj = self.fields[field_name]\n            except KeyError:\n                if field_name in self.declared_fields:\n                    continue\n                raise ValueError('\"{0}\" field does not exist.'.format(field_name))\n\n            if many:\n                for idx, item in enumerate(data):\n                    try:\n                        value = item[field_obj.attribute or field_name]\n                    except KeyError:\n                        pass\n                    else:\n                        validated_value = unmarshal.call_and_store(\n                            getter_func=validator,\n                            data=value,\n                            field_name=field_obj.load_from or field_name,\n                            field_obj=field_obj,\n                            index=(idx if self.opts.index_errors else None)\n                        )\n                        if validated_value is missing:\n                            data[idx].pop(field_name, None)\n            else:\n                try:\n                    value = data[field_obj.attribute or field_name]\n                except KeyError:\n                    pass\n                else:\n                    validated_value = unmarshal.call_and_store(\n                        getter_func=validator,\n                        data=value,\n                        field_name=field_obj.load_from or field_name,\n                        field_obj=field_obj\n                    )\n                    if validated_value is missing:\n                        data.pop(field_name, None)\n\n    def _invoke_validators(\n            self, unmarshal, pass_many, data, original_data, many, field_errors=False):\n        errors = {}\n        for attr_name in self.__processors__[(VALIDATES_SCHEMA, pass_many)]:\n            validator = getattr(self, attr_name)\n            validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATES_SCHEMA, pass_many)]\n            pass_original = validator_kwargs.get('pass_original', False)\n\n            skip_on_field_errors = validator_kwargs['skip_on_field_errors']\n            if skip_on_field_errors and field_errors:\n                continue\n\n            if pass_many:\n                validator = functools.partial(validator, many=many)\n            if many and not pass_many:\n                for idx, item in enumerate(data):\n                    try:\n                        unmarshal.run_validator(validator,\n                                                item, original_data, self.fields, many=many,\n                                                index=idx, pass_original=pass_original)\n                    except ValidationError as err:\n                        errors.update(err.messages)\n            else:\n                try:\n                    unmarshal.run_validator(validator,\n                                            data, original_data, self.fields, many=many,\n                                            pass_original=pass_original)\n                except ValidationError as err:\n                    errors.update(err.messages)\n        if errors:\n            raise ValidationError(errors)\n        return None\n\n    def _invoke_processors(self, tag_name, pass_many, data, many, original_data=None):\n        for attr_name in self.__processors__[(tag_name, pass_many)]:\n            # This will be a bound method.\n            processor = getattr(self, attr_name)\n\n            processor_kwargs = processor.__marshmallow_kwargs__[(tag_name, pass_many)]\n            pass_original = processor_kwargs.get('pass_original', False)\n\n            if pass_many:\n                if pass_original:\n                    data = utils.if_none(processor(data, many, original_data), data)\n                else:\n                    data = utils.if_none(processor(data, many), data)\n            elif many:\n                if pass_original:\n                    data = [utils.if_none(processor(item, original_data), item)\n                            for item in data]\n                else:\n                    data = [utils.if_none(processor(item), item) for item in data]\n            else:\n                if pass_original:\n                    data = utils.if_none(processor(data, original_data), data)\n                else:\n                    data = utils.if_none(processor(data), data)\n        return data\n\n\nclass Schema(with_metaclass(SchemaMeta, BaseSchema)):\n    __doc__ = BaseSchema.__doc__\n"}
filelevel_patches: {"src/marshmallow/schema.py": "@@ -877,7 +877,7 @@ def _invoke_field_validators(self, unmarshal, data, many):\n                 for idx, item in enumerate(data):\n                     try:\n                         value = item[field_obj.attribute or field_name]\n-                    except KeyError:\n+                    except (KeyError, TypeError):\n                         pass\n                     else:\n                         validated_value = unmarshal.call_and_store(\n@@ -892,7 +892,7 @@ def _invoke_field_validators(self, unmarshal, data, many):\n             else:\n                 try:\n                     value = data[field_obj.attribute or field_name]\n-                except KeyError:\n+                except (KeyError, TypeError):\n                     pass\n                 else:\n                     validated_value = unmarshal.call_and_store("}
messages.content: 
  We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  [version 2.20.0] TypeError: 'NoneType' object is not subscriptable
  After update from version 2.19.5 to 2.20.0 I got error for code like:
  
  ```python
  from marshmallow import Schema, fields, validates
  
  
  class Bar(Schema):
      value = fields.String()
  
      @validates('value')  # <- issue here
      def validate_value(self, value):
          pass
  
  
  class Foo(Schema):
      bar = fields.Nested(Bar)
  
  
  sch = Foo()
  
  sch.validate({
      'bar': 'invalid',
  })
  ```
  
  ```
  Traceback (most recent call last):
    File "/_/bug_mschema.py", line 19, in <module>
      'bar': 'invalid',
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 628, in validate
      _, errors = self._do_load(data, many, partial=partial, postprocess=False)
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 670, in _do_load
      index_errors=self.opts.index_errors,
    File "/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py", line 292, in deserialize
      index=(index if index_errors else None)
    File "/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py", line 65, in call_and_store
      value = getter_func(data)
    File "/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py", line 285, in <lambda>
      data
    File "/_/env/lib/python3.7/site-packages/marshmallow/fields.py", line 265, in deserialize
      output = self._deserialize(value, attr, data)
    File "/_/env/lib/python3.7/site-packages/marshmallow/fields.py", line 465, in _deserialize
      data, errors = self.schema.load(value)
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 588, in load
      result, errors = self._do_load(data, many, partial=partial, postprocess=True)
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 674, in _do_load
      self._invoke_field_validators(unmarshal, data=result, many=many)
    File "/_/env/lib/python3.7/site-packages/marshmallow/schema.py", line 894, in _invoke_field_validators
      value = data[field_obj.attribute or field_name]
  TypeError: 'NoneType' object is not subscriptable
  ```
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  
  --- BEGIN FILE ---
  ```
  ### src/marshmallow/schema.py
  # -*- coding: utf-8 -*-
  """The :class:`Schema` class, including its metaclass and options (class Meta)."""
  from __future__ import absolute_import, unicode_literals
  
  from collections import defaultdict, namedtuple
  import copy
  import datetime as dt
  import decimal
  import inspect
  import json
  import uuid
  import warnings
  import functools
  
  from marshmallow import base, fields, utils, class_registry, marshalling
  from marshmallow.compat import (with_metaclass, iteritems, text_type,
                                  binary_type, Mapping, OrderedDict)
  from marshmallow.exceptions import ValidationError
  from marshmallow.orderedset import OrderedSet
  from marshmallow.decorators import (PRE_DUMP, POST_DUMP, PRE_LOAD, POST_LOAD,
                                      VALIDATES, VALIDATES_SCHEMA)
  from marshmallow.utils import missing
  from marshmallow.warnings import RemovedInMarshmallow3Warning, ChangedInMarshmallow3Warning
  
  
  #: Return type of :meth:`Schema.dump` including serialized data and errors
  MarshalResult = namedtuple('MarshalResult', ['data', 'errors'])
  #: Return type of :meth:`Schema.load`, including deserialized data and errors
  UnmarshalResult = namedtuple('UnmarshalResult', ['data', 'errors'])
  
  def _get_fields(attrs, field_class, pop=False, ordered=False):
      """Get fields from a class. If ordered=True, fields will sorted by creation index.
  
      :param attrs: Mapping of class attributes
      :param type field_class: Base field class
      :param bool pop: Remove matching fields
      """
      getter = getattr(attrs, 'pop' if pop else 'get')
      fields = [
          (field_name, getter(field_name))
          for field_name, field_value in list(iteritems(attrs))
          if utils.is_instance_or_subclass(field_value, field_class)
      ]
      if ordered:
          return sorted(
              fields,
              key=lambda pair: pair[1]._creation_index,
          )
      else:
          return fields
  
  # This function allows Schemas to inherit from non-Schema classes and ensures
  #   inheritance according to the MRO
  def _get_fields_by_mro(klass, field_class, ordered=False):
      """Collect fields from a class, following its method resolution order. The
      class itself is excluded from the search; only its parents are checked. Get
      fields from ``_declared_fields`` if available, else use ``__dict__``.
  
      :param type klass: Class whose fields to retrieve
      :param type field_class: Base field class
      """
      mro = inspect.getmro(klass)
      # Loop over mro in reverse to maintain correct order of fields
      return sum(
          (
              _get_fields(
                  getattr(base, '_declared_fields', base.__dict__),
                  field_class,
                  ordered=ordered
              )
              for base in mro[:0:-1]
          ),
          [],
      )
  
  
  class SchemaMeta(type):
      """Metaclass for the Schema class. Binds the declared fields to
      a ``_declared_fields`` attribute, which is a dictionary mapping attribute
      names to field objects. Also sets the ``opts`` class attribute, which is
      the Schema class's ``class Meta`` options.
      """
  
      def __new__(mcs, name, bases, attrs):
          meta = attrs.get('Meta')
          ordered = getattr(meta, 'ordered', False)
          if not ordered:
              # Inherit 'ordered' option
              # Warning: We loop through bases instead of MRO because we don't
              # yet have access to the class object
              # (i.e. can't call super before we have fields)
              for base_ in bases:
                  if hasattr(base_, 'Meta') and hasattr(base_.Meta, 'ordered'):
                      ordered = base_.Meta.ordered
                      break
              else:
                  ordered = False
          cls_fields = _get_fields(attrs, base.FieldABC, pop=True, ordered=ordered)
          klass = super(SchemaMeta, mcs).__new__(mcs, name, bases, attrs)
          inherited_fields = _get_fields_by_mro(klass, base.FieldABC, ordered=ordered)
  
          # Use getattr rather than attrs['Meta'] so that we get inheritance for free
          meta = getattr(klass, 'Meta')
          # Set klass.opts in __new__ rather than __init__ so that it is accessible in
          # get_declared_fields
          klass.opts = klass.OPTIONS_CLASS(meta)
          # Pass the inherited `ordered` into opts
          klass.opts.ordered = ordered
          # Add fields specifid in the `include` class Meta option
          cls_fields += list(klass.opts.include.items())
  
          dict_cls = OrderedDict if ordered else dict
          # Assign _declared_fields on class
          klass._declared_fields = mcs.get_declared_fields(
              klass=klass,
              cls_fields=cls_fields,
              inherited_fields=inherited_fields,
              dict_cls=dict_cls
          )
          return klass
  
      @classmethod
      def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls):
          """Returns a dictionary of field_name => `Field` pairs declard on the class.
          This is exposed mainly so that plugins can add additional fields, e.g. fields
          computed from class Meta options.
  
          :param type klass: The class object.
          :param dict cls_fields: The fields declared on the class, including those added
              by the ``include`` class Meta option.
          :param dict inherited_fileds: Inherited fields.
          :param type dict_class: Either `dict` or `OrderedDict`, depending on the whether
              the user specified `ordered=True`.
          """
          return dict_cls(inherited_fields + cls_fields)
  
      # NOTE: self is the class object
      def __init__(self, name, bases, attrs):
          super(SchemaMeta, self).__init__(name, bases, attrs)
          if name:
              class_registry.register(name, self)
          self._resolve_processors()
  
      def _resolve_processors(self):
          """Add in the decorated processors
  
          By doing this after constructing the class, we let standard inheritance
          do all the hard work.
          """
          mro = inspect.getmro(self)
          self._has_processors = False
          self.__processors__ = defaultdict(list)
          for attr_name in dir(self):
              # Need to look up the actual descriptor, not whatever might be
              # bound to the class. This needs to come from the __dict__ of the
              # declaring class.
              for parent in mro:
                  try:
                      attr = parent.__dict__[attr_name]
                  except KeyError:
                      continue
                  else:
                      break
              else:
                  # In case we didn't find the attribute and didn't break above.
                  # We should never hit this - it's just here for completeness
                  # to exclude the possibility of attr being undefined.
                  continue
  
              try:
                  processor_tags = attr.__marshmallow_tags__
              except AttributeError:
                  continue
  
              self._has_processors = bool(processor_tags)
              for tag in processor_tags:
                  # Use name here so we can get the bound method later, in case
                  # the processor was a descriptor or something.
                  self.__processors__[tag].append(attr_name)
  
  
  class SchemaOpts(object):
      """class Meta options for the :class:`Schema`. Defines defaults."""
  
      def __init__(self, meta):
          self.fields = getattr(meta, 'fields', ())
          if not isinstance(self.fields, (list, tuple)):
              raise ValueError("`fields` option must be a list or tuple.")
          self.additional = getattr(meta, 'additional', ())
          if not isinstance(self.additional, (list, tuple)):
              raise ValueError("`additional` option must be a list or tuple.")
          if self.fields and self.additional:
              raise ValueError("Cannot set both `fields` and `additional` options"
                              " for the same Schema.")
          self.exclude = getattr(meta, 'exclude', ())
          if not isinstance(self.exclude, (list, tuple)):
              raise ValueError("`exclude` must be a list or tuple.")
          self.strict = getattr(meta, 'strict', False)
          if hasattr(meta, 'dateformat'):
              warnings.warn(
                  "The dateformat option is renamed to datetimeformat in marshmallow 3.",
                  ChangedInMarshmallow3Warning
              )
          self.dateformat = getattr(meta, 'dateformat', None)
          if hasattr(meta, 'json_module'):
              warnings.warn(
                  "The json_module option is renamed to render_module in marshmallow 3.",
                  ChangedInMarshmallow3Warning
              )
          self.json_module = getattr(meta, 'json_module', json)
          if hasattr(meta, 'skip_missing'):
              warnings.warn(
                  'The skip_missing option is no longer necessary. Missing inputs passed to '
                  'Schema.dump will be excluded from the serialized output by default.',
                  UserWarning
              )
          self.ordered = getattr(meta, 'ordered', False)
          self.index_errors = getattr(meta, 'index_errors', True)
          self.include = getattr(meta, 'include', {})
          self.load_only = getattr(meta, 'load_only', ())
          self.dump_only = getattr(meta, 'dump_only', ())
  
  
  class BaseSchema(base.SchemaABC):
      """Base schema class with which to define custom schemas.
  
      Example usage:
  
      .. code-block:: python
  
          import datetime as dt
          from marshmallow import Schema, fields
  
          class Album(object):
              def __init__(self, title, release_date):
                  self.title = title
                  self.release_date = release_date
  
          class AlbumSchema(Schema):
              title = fields.Str()
              release_date = fields.Date()
  
          # Or, equivalently
          class AlbumSchema2(Schema):
              class Meta:
                  fields = ("title", "release_date")
  
          album = Album("Beggars Banquet", dt.date(1968, 12, 6))
          schema = AlbumSchema()
          data, errors = schema.dump(album)
          data  # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'}
  
      :param dict extra: A dict of extra attributes to bind to the serialized result.
      :param tuple|list only: Whitelist of fields to select when instantiating the Schema.
          If None, all fields are used.
          Nested fields can be represented with dot delimiters.
      :param tuple|list exclude: Blacklist of fields to exclude when instantiating the Schema.
          If a field appears in both `only` and `exclude`, it is not used.
          Nested fields can be represented with dot delimiters.
      :param str prefix: Optional prefix that will be prepended to all the
          serialized field names.
      :param bool strict: If `True`, raise errors if invalid data are passed in
          instead of failing silently and storing the errors.
      :param bool many: Should be set to `True` if ``obj`` is a collection
          so that the object will be serialized to a list.
      :param dict context: Optional context passed to :class:`fields.Method` and
          :class:`fields.Function` fields.
      :param tuple|list load_only: Fields to skip during serialization (write-only fields)
      :param tuple|list dump_only: Fields to skip during deserialization (read-only fields)
      :param bool|tuple partial: Whether to ignore missing fields. If its value
          is an iterable, only missing fields listed in that iterable will be
          ignored.
  
      .. versionchanged:: 2.0.0
          `__validators__`, `__preprocessors__`, and `__data_handlers__` are removed in favor of
          `marshmallow.decorators.validates_schema`,
          `marshmallow.decorators.pre_load` and `marshmallow.decorators.post_dump`.
          `__accessor__` and `__error_handler__` are deprecated. Implement the
          `handle_error` and `get_attribute` methods instead.
          """
      TYPE_MAPPING = {
          text_type: fields.String,
          binary_type: fields.String,
          dt.datetime: fields.DateTime,
          float: fields.Float,
          bool: fields.Boolean,
          tuple: fields.Raw,
          list: fields.Raw,
          set: fields.Raw,
          int: fields.Integer,
          uuid.UUID: fields.UUID,
          dt.time: fields.Time,
          dt.date: fields.Date,
          dt.timedelta: fields.TimeDelta,
          decimal.Decimal: fields.Decimal,
      }
  
      OPTIONS_CLASS = SchemaOpts
  
      #: DEPRECATED: Custom error handler function. May be `None`.
      __error_handler__ = None
      #: DEPRECATED: Function used to get values of an object.
      __accessor__ = None
  
      class Meta(object):
          """Options object for a Schema.
  
          Example usage: ::
  
              class Meta:
                  fields = ("id", "email", "date_created")
                  exclude = ("password", "secret_attribute")
  
          Available options:
  
          - ``fields``: Tuple or list of fields to include in the serialized result.
          - ``additional``: Tuple or list of fields to include *in addition* to the
              explicitly declared fields. ``additional`` and ``fields`` are
              mutually-exclusive options.
          - ``include``: Dictionary of additional fields to include in the schema. It is
              usually better to define fields as class variables, but you may need to
              use this option, e.g., if your fields are Python keywords. May be an
              `OrderedDict`.
          - ``exclude``: Tuple or list of fields to exclude in the serialized result.
              Nested fields can be represented with dot delimiters.
          - ``dateformat``: Date format for all DateTime fields that do not have their
              date format explicitly specified.
          - ``strict``: If `True`, raise errors during marshalling rather than
              storing them.
          - ``json_module``: JSON module to use for `loads` and `dumps`.
              Defaults to the ``json`` module in the stdlib.
          - ``ordered``: If `True`, order serialization output according to the
              order in which fields were declared. Output of `Schema.dump` will be a
              `collections.OrderedDict`.
          - ``index_errors``: If `True`, errors dictionaries will include the index
              of invalid items in a collection.
          - ``load_only``: Tuple or list of fields to exclude from serialized results.
          - ``dump_only``: Tuple or list of fields to exclude from deserialization
          """
          pass
  
      def __init__(self, extra=None, only=None, exclude=(), prefix='', strict=None,
                   many=False, context=None, load_only=(), dump_only=(),
                   partial=False):
          # copy declared fields from metaclass
          self.declared_fields = copy.deepcopy(self._declared_fields)
          self.many = many
          self.only = only
          self.exclude = set(self.opts.exclude) | set(exclude)
          if prefix:
              warnings.warn(
                  'The `prefix` argument is deprecated. Use a post_dump '
                  'method to insert a prefix instead.',
                  RemovedInMarshmallow3Warning
              )
          self.prefix = prefix
          self.strict = strict if strict is not None else self.opts.strict
          self.ordered = self.opts.ordered
          self.load_only = set(load_only) or set(self.opts.load_only)
          self.dump_only = set(dump_only) or set(self.opts.dump_only)
          self.partial = partial
          #: Dictionary mapping field_names -> :class:`Field` objects
          self.fields = self.dict_class()
          if extra:
              warnings.warn(
                  'The `extra` argument is deprecated. Use a post_dump '
                  'method to add additional data instead.',
                  RemovedInMarshmallow3Warning
              )
          self.extra = extra
          self.context = context or {}
          self._normalize_nested_options()
          self._types_seen = set()
          self._update_fields(many=many)
  
      def __repr__(self):
          return '<{ClassName}(many={self.many}, strict={self.strict})>'.format(
              ClassName=self.__class__.__name__, self=self
          )
  
      def _postprocess(self, data, many, obj):
          if self.extra:
              if many:
                  for each in data:
                      each.update(self.extra)
              else:
                  data.update(self.extra)
          return data
  
      @property
      def dict_class(self):
          return OrderedDict if self.ordered else dict
  
      @property
      def set_class(self):
          return OrderedSet if self.ordered else set
  
      ##### Override-able methods #####
  
      def handle_error(self, error, data):
          """Custom error handler function for the schema.
  
          :param ValidationError error: The `ValidationError` raised during (de)serialization.
          :param data: The original input data.
  
          .. versionadded:: 2.0.0
          """
          pass
  
      def get_attribute(self, attr, obj, default):
          """Defines how to pull values from an object to serialize.
  
          .. versionadded:: 2.0.0
          """
          return utils.get_value(attr, obj, default)
  
      ##### Handler decorators (deprecated) #####
  
      @classmethod
      def error_handler(cls, func):
          """Decorator that registers an error handler function for the schema.
          The function receives the :class:`Schema` instance, a dictionary of errors,
          and the serialized object (if serializing data) or data dictionary (if
          deserializing data) as arguments.
  
          Example: ::
  
              class UserSchema(Schema):
                  email = fields.Email()
  
              @UserSchema.error_handler
              def handle_errors(schema, errors, obj):
                  raise ValueError('An error occurred while marshalling {}'.format(obj))
  
              user = User(email='invalid')
              UserSchema().dump(user)  # => raises ValueError
              UserSchema().load({'email': 'bademail'})  # raises ValueError
  
          .. versionadded:: 0.7.0
          .. deprecated:: 2.0.0
              Set the ``error_handler`` class Meta option instead.
          """
          warnings.warn(
              'Schema.error_handler is deprecated. Set the error_handler class Meta option '
              'instead.', category=DeprecationWarning
          )
          cls.__error_handler__ = func
          return func
  
      @classmethod
      def accessor(cls, func):
          """Decorator that registers a function for pulling values from an object
          to serialize. The function receives the :class:`Schema` instance, the
          ``key`` of the value to get, the ``obj`` to serialize, and an optional
          ``default`` value.
  
          .. deprecated:: 2.0.0
              Set the ``error_handler`` class Meta option instead.
          """
          warnings.warn(
              'Schema.accessor is deprecated. Set the accessor class Meta option '
              'instead.', category=DeprecationWarning
          )
          cls.__accessor__ = func
          return func
  
      ##### Serialization/Deserialization API #####
  
      def dump(self, obj, many=None, update_fields=True, **kwargs):
          """Serialize an object to native Python data types according to this
          Schema's fields.
  
          :param obj: The object to serialize.
          :param bool many: Whether to serialize `obj` as a collection. If `None`, the value
              for `self.many` is used.
          :param bool update_fields: Whether to update the schema's field classes. Typically
              set to `True`, but may be `False` when serializing a homogenous collection.
              This parameter is used by `fields.Nested` to avoid multiple updates.
          :return: A tuple of the form (``data``, ``errors``)
          :rtype: `MarshalResult`, a `collections.namedtuple`
  
          .. versionadded:: 1.0.0
          """
          # Callable marshalling object
          marshal = marshalling.Marshaller(prefix=self.prefix)
          errors = {}
          many = self.many if many is None else bool(many)
          if many and utils.is_iterable_but_not_string(obj):
              obj = list(obj)
  
          if self._has_processors:
              try:
                  processed_obj = self._invoke_dump_processors(
                      PRE_DUMP,
                      obj,
                      many,
                      original_data=obj)
              except ValidationError as error:
                  errors = error.normalized_messages()
                  result = None
          else:
              processed_obj = obj
  
          if not errors:
              if update_fields:
                  obj_type = type(processed_obj)
                  if obj_type not in self._types_seen:
                      self._update_fields(processed_obj, many=many)
                      if not isinstance(processed_obj, Mapping):
                          self._types_seen.add(obj_type)
  
              try:
                  preresult = marshal(
                      processed_obj,
                      self.fields,
                      many=many,
                      # TODO: Remove self.__accessor__ in a later release
                      accessor=self.get_attribute or self.__accessor__,
                      dict_class=self.dict_class,
                      index_errors=self.opts.index_errors,
                      **kwargs
                  )
              except ValidationError as error:
                  errors = marshal.errors
                  preresult = error.data
  
              result = self._postprocess(preresult, many, obj=obj)
  
          if not errors and self._has_processors:
              try:
                  result = self._invoke_dump_processors(
                      POST_DUMP,
                      result,
                      many,
                      original_data=obj)
              except ValidationError as error:
                  errors = error.normalized_messages()
          if errors:
              # TODO: Remove self.__error_handler__ in a later release
              if self.__error_handler__ and callable(self.__error_handler__):
                  self.__error_handler__(errors, obj)
              exc = ValidationError(
                  errors,
                  field_names=marshal.error_field_names,
                  fields=marshal.error_fields,
                  data=obj,
                  **marshal.error_kwargs
              )
              self.handle_error(exc, obj)
              if self.strict:
                  raise exc
  
          return MarshalResult(result, errors)
  
      def dumps(self, obj, many=None, update_fields=True, *args, **kwargs):
          """Same as :meth:`dump`, except return a JSON-encoded string.
  
          :param obj: The object to serialize.
          :param bool many: Whether to serialize `obj` as a collection. If `None`, the value
              for `self.many` is used.
          :param bool update_fields: Whether to update the schema's field classes. Typically
              set to `True`, but may be `False` when serializing a homogenous collection.
              This parameter is used by `fields.Nested` to avoid multiple updates.
          :return: A tuple of the form (``data``, ``errors``)
          :rtype: `MarshalResult`, a `collections.namedtuple`
  
          .. versionadded:: 1.0.0
          """
          deserialized, errors = self.dump(obj, many=many, update_fields=update_fields)
          ret = self.opts.json_module.dumps(deserialized, *args, **kwargs)
          return MarshalResult(ret, errors)
  
      def load(self, data, many=None, partial=None):
          """Deserialize a data structure to an object defined by this Schema's
          fields and :meth:`make_object`.
  
          :param dict data: The data to deserialize.
          :param bool many: Whether to deserialize `data` as a collection. If `None`, the
              value for `self.many` is used.
          :param bool|tuple partial: Whether to ignore missing fields. If `None`,
              the value for `self.partial` is used. If its value is an iterable,
              only missing fields listed in that iterable will be ignored.
          :return: A tuple of the form (``data``, ``errors``)
          :rtype: `UnmarshalResult`, a `collections.namedtuple`
  
          .. versionadded:: 1.0.0
          """
          result, errors = self._do_load(data, many, partial=partial, postprocess=True)
          return UnmarshalResult(data=result, errors=errors)
  
      def loads(self, json_data, many=None, *args, **kwargs):
          """Same as :meth:`load`, except it takes a JSON string as input.
  
          :param str json_data: A JSON string of the data to deserialize.
          :param bool many: Whether to deserialize `obj` as a collection. If `None`, the
              value for `self.many` is used.
          :param bool|tuple partial: Whether to ignore missing fields. If `None`,
              the value for `self.partial` is used. If its value is an iterable,
              only missing fields listed in that iterable will be ignored.
          :return: A tuple of the form (``data``, ``errors``)
          :rtype: `UnmarshalResult`, a `collections.namedtuple`
  
          .. versionadded:: 1.0.0
          """
          # TODO: This avoids breaking backward compatibility if people were
          # passing in positional args after `many` for use by `json.loads`, but
          # ideally we shouldn't have to do this.
          partial = kwargs.pop('partial', None)
  
          data = self.opts.json_module.loads(json_data, *args, **kwargs)
          return self.load(data, many=many, partial=partial)
  
      def validate(self, data, many=None, partial=None):
          """Validate `data` against the schema, returning a dictionary of
          validation errors.
  
          :param dict data: The data to validate.
          :param bool many: Whether to validate `data` as a collection. If `None`, the
              value for `self.many` is used.
          :param bool|tuple partial: Whether to ignore missing fields. If `None`,
              the value for `self.partial` is used. If its value is an iterable,
              only missing fields listed in that iterable will be ignored.
          :return: A dictionary of validation errors.
          :rtype: dict
  
          .. versionadded:: 1.1.0
          """
          _, errors = self._do_load(data, many, partial=partial, postprocess=False)
          return errors
  
      ##### Private Helpers #####
  
      def _do_load(self, data, many=None, partial=None, postprocess=True):
          """Deserialize `data`, returning the deserialized result and a dictonary of
          validation errors.
  
          :param data: The data to deserialize.
          :param bool many: Whether to deserialize `data` as a collection. If `None`, the
              value for `self.many` is used.
          :param bool|tuple partial: Whether to validate required fields. If its value is an iterable,
              only fields listed in that iterable will be ignored will be allowed missing.
              If `True`, all fields will be allowed missing.
              If `None`, the value for `self.partial` is used.
          :param bool postprocess: Whether to run post_load methods..
          :return: A tuple of the form (`data`, `errors`)
          """
          # Callable unmarshalling object
          unmarshal = marshalling.Unmarshaller()
          errors = {}
          many = self.many if many is None else bool(many)
          if partial is None:
              partial = self.partial
          try:
              processed_data = self._invoke_load_processors(
                  PRE_LOAD,
                  data,
                  many,
                  original_data=data)
          except ValidationError as err:
              errors = err.normalized_messages()
              result = None
          if not errors:
              try:
                  result = unmarshal(
                      processed_data,
                      self.fields,
                      many=many,
                      partial=partial,
                      dict_class=self.dict_class,
                      index_errors=self.opts.index_errors,
                  )
              except ValidationError as error:
                  result = error.data
              self._invoke_field_validators(unmarshal, data=result, many=many)
              errors = unmarshal.errors
              field_errors = bool(errors)
              # Run schema-level migration
              try:
                  self._invoke_validators(unmarshal, pass_many=True, data=result, original_data=data,
                                          many=many, field_errors=field_errors)
              except ValidationError as err:
                  errors.update(err.messages)
              try:
                  self._invoke_validators(unmarshal, pass_many=False, data=result, original_data=data,
                                          many=many, field_errors=field_errors)
              except ValidationError as err:
                  errors.update(err.messages)
          # Run post processors
          if not errors and postprocess:
              try:
                  result = self._invoke_load_processors(
                      POST_LOAD,
                      result,
                      many,
                      original_data=data)
              except ValidationError as err:
                  errors = err.normalized_messages()
          if errors:
              # TODO: Remove self.__error_handler__ in a later release
              if self.__error_handler__ and callable(self.__error_handler__):
                  self.__error_handler__(errors, data)
              exc = ValidationError(
                  errors,
                  field_names=unmarshal.error_field_names,
                  fields=unmarshal.error_fields,
                  data=data,
                  **unmarshal.error_kwargs
              )
              self.handle_error(exc, data)
              if self.strict:
                  raise exc
  
          return result, errors
  
      def _normalize_nested_options(self):
          """Apply then flatten nested schema options"""
          if self.only is not None:
              # Apply the only option to nested fields.
              self.__apply_nested_option('only', self.only, 'intersection')
              # Remove the child field names from the only option.
              self.only = self.set_class(
                  [field.split('.', 1)[0] for field in self.only],
              )
          if self.exclude:
              # Apply the exclude option to nested fields.
              self.__apply_nested_option('exclude', self.exclude, 'union')
              # Remove the parent field names from the exclude option.
              self.exclude = self.set_class(
                  [field for field in self.exclude if '.' not in field],
              )
  
      def __apply_nested_option(self, option_name, field_names, set_operation):
          """Apply nested options to nested fields"""
          # Split nested field names on the first dot.
          nested_fields = [name.split('.', 1) for name in field_names if '.' in name]
          # Partition the nested field names by parent field.
          nested_options = defaultdict(list)
          for parent, nested_names in nested_fields:
              nested_options[parent].append(nested_names)
          # Apply the nested field options.
          for key, options in iter(nested_options.items()):
              new_options = self.set_class(options)
              original_options = getattr(self.declared_fields[key], option_name, ())
              if original_options:
                  if set_operation == 'union':
                      new_options |= self.set_class(original_options)
                  if set_operation == 'intersection':
                      new_options &= self.set_class(original_options)
              setattr(self.declared_fields[key], option_name, new_options)
  
      def _update_fields(self, obj=None, many=False):
          """Update fields based on the passed in object."""
          if self.only is not None:
              # Return only fields specified in only option
              if self.opts.fields:
                  field_names = self.set_class(self.opts.fields) & self.set_class(self.only)
              else:
                  field_names = self.set_class(self.only)
          elif self.opts.fields:
              # Return fields specified in fields option
              field_names = self.set_class(self.opts.fields)
          elif self.opts.additional:
              # Return declared fields + additional fields
              field_names = (self.set_class(self.declared_fields.keys()) |
                              self.set_class(self.opts.additional))
          else:
              field_names = self.set_class(self.declared_fields.keys())
  
          # If "exclude" option or param is specified, remove those fields
          field_names -= self.exclude
          ret = self.__filter_fields(field_names, obj, many=many)
          # Set parents
          self.__set_field_attrs(ret)
          self.fields = ret
          return self.fields
  
      def on_bind_field(self, field_name, field_obj):
          """Hook to modify a field when it is bound to the `Schema`. No-op by default."""
          return None
  
      def __set_field_attrs(self, fields_dict):
          """Bind fields to the schema, setting any necessary attributes
          on the fields (e.g. parent and name).
  
          Also set field load_only and dump_only values if field_name was
          specified in ``class Meta``.
          """
          for field_name, field_obj in iteritems(fields_dict):
              try:
                  if field_name in self.load_only:
                      field_obj.load_only = True
                  if field_name in self.dump_only:
                      field_obj.dump_only = True
                  field_obj._add_to_schema(field_name, self)
                  self.on_bind_field(field_name, field_obj)
              except TypeError:
                  # field declared as a class, not an instance
                  if (isinstance(field_obj, type) and
                          issubclass(field_obj, base.FieldABC)):
                      msg = ('Field for "{0}" must be declared as a '
                             'Field instance, not a class. '
                             'Did you mean "fields.{1}()"?'
                             .format(field_name, field_obj.__name__))
                      raise TypeError(msg)
          return fields_dict
  
      def __filter_fields(self, field_names, obj, many=False):
          """Return only those field_name:field_obj pairs specified by
          ``field_names``.
  
          :param set field_names: Field names to include in the final
              return dictionary.
          :param object|Mapping|list obj The object to base filtered fields on.
          :returns: An dict of field_name:field_obj pairs.
          """
          if obj and many:
              try:  # list
                  obj = obj[0]
              except IndexError:  # Nothing to serialize
                  return dict((k, v) for k, v in self.declared_fields.items() if k in field_names)
          ret = self.dict_class()
          for key in field_names:
              if key in self.declared_fields:
                  ret[key] = self.declared_fields[key]
              else:  # Implicit field creation (class Meta 'fields' or 'additional')
                  if obj:
                      attribute_type = None
                      try:
                          if isinstance(obj, Mapping):
                              attribute_type = type(obj[key])
                          else:
                              attribute_type = type(getattr(obj, key))
                      except (AttributeError, KeyError) as err:
                          err_type = type(err)
                          raise err_type(
                              '"{0}" is not a valid field for {1}.'.format(key, obj))
                      field_obj = self.TYPE_MAPPING.get(attribute_type, fields.Field)()
                  else:  # Object is None
                      field_obj = fields.Field()
                  # map key -> field (default to Raw)
                  ret[key] = field_obj
          return ret
  
      def _invoke_dump_processors(self, tag_name, data, many, original_data=None):
          # The pass_many post-dump processors may do things like add an envelope, so
          # invoke those after invoking the non-pass_many processors which will expect
          # to get a list of items.
          data = self._invoke_processors(tag_name, pass_many=False,
              data=data, many=many, original_data=original_data)
          data = self._invoke_processors(tag_name, pass_many=True,
              data=data, many=many, original_data=original_data)
          return data
  
      def _invoke_load_processors(self, tag_name, data, many, original_data=None):
          # This has to invert the order of the dump processors, so run the pass_many
          # processors first.
          data = self._invoke_processors(tag_name, pass_many=True,
              data=data, many=many, original_data=original_data)
          data = self._invoke_processors(tag_name, pass_many=False,
              data=data, many=many, original_data=original_data)
          return data
  
      def _invoke_field_validators(self, unmarshal, data, many):
          for attr_name in self.__processors__[(VALIDATES, False)]:
              validator = getattr(self, attr_name)
              validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATES, False)]
              field_name = validator_kwargs['field_name']
  
              try:
                  field_obj = self.fields[field_name]
              except KeyError:
                  if field_name in self.declared_fields:
                      continue
                  raise ValueError('"{0}" field does not exist.'.format(field_name))
  
              if many:
                  for idx, item in enumerate(data):
                      try:
                          value = item[field_obj.attribute or field_name]
                      except KeyError:
                          pass
                      else:
                          validated_value = unmarshal.call_and_store(
                              getter_func=validator,
                              data=value,
                              field_name=field_obj.load_from or field_name,
                              field_obj=field_obj,
                              index=(idx if self.opts.index_errors else None)
                          )
                          if validated_value is missing:
                              data[idx].pop(field_name, None)
              else:
                  try:
                      value = data[field_obj.attribute or field_name]
                  except KeyError:
                      pass
                  else:
                      validated_value = unmarshal.call_and_store(
                          getter_func=validator,
                          data=value,
                          field_name=field_obj.load_from or field_name,
                          field_obj=field_obj
                      )
                      if validated_value is missing:
                          data.pop(field_name, None)
  
      def _invoke_validators(
              self, unmarshal, pass_many, data, original_data, many, field_errors=False):
          errors = {}
          for attr_name in self.__processors__[(VALIDATES_SCHEMA, pass_many)]:
              validator = getattr(self, attr_name)
              validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATES_SCHEMA, pass_many)]
              pass_original = validator_kwargs.get('pass_original', False)
  
              skip_on_field_errors = validator_kwargs['skip_on_field_errors']
              if skip_on_field_errors and field_errors:
                  continue
  
              if pass_many:
                  validator = functools.partial(validator, many=many)
              if many and not pass_many:
                  for idx, item in enumerate(data):
                      try:
                          unmarshal.run_validator(validator,
                                                  item, original_data, self.fields, many=many,
                                                  index=idx, pass_original=pass_original)
                      except ValidationError as err:
                          errors.update(err.messages)
              else:
                  try:
                      unmarshal.run_validator(validator,
                                              data, original_data, self.fields, many=many,
                                              pass_original=pass_original)
                  except ValidationError as err:
                      errors.update(err.messages)
          if errors:
              raise ValidationError(errors)
          return None
  
      def _invoke_processors(self, tag_name, pass_many, data, many, original_data=None):
          for attr_name in self.__processors__[(tag_name, pass_many)]:
              # This will be a bound method.
              processor = getattr(self, attr_name)
  
              processor_kwargs = processor.__marshmallow_kwargs__[(tag_name, pass_many)]
              pass_original = processor_kwargs.get('pass_original', False)
  
              if pass_many:
                  if pass_original:
                      data = utils.if_none(processor(data, many, original_data), data)
                  else:
                      data = utils.if_none(processor(data, many), data)
              elif many:
                  if pass_original:
                      data = [utils.if_none(processor(item, original_data), item)
                              for item in data]
                  else:
                      data = [utils.if_none(processor(item), item) for item in data]
              else:
                  if pass_original:
                      data = utils.if_none(processor(data, original_data), data)
                  else:
                      data = utils.if_none(processor(data), data)
          return data
  
  
  class Schema(with_metaclass(SchemaMeta, BaseSchema)):
      __doc__ = BaseSchema.__doc__
  
  ```
  --- END FILE ---
  
  Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.
  
  Every *SEARCH/REPLACE* edit must use this format:
  1. The file path
  2. The start of search block: <<<<<<< SEARCH
  3. A contiguous chunk of lines to search for in the existing source code
  4. The dividing line: =======
  5. The lines to replace into the source code
  6. The end of the replace block: >>>>>>> REPLACE
  
  Here is an example:
  
  ```python
  ### mathweb/flask/app.py
  <<<<<<< SEARCH
  from flask import Flask
  =======
  import math
  from flask import Flask
  >>>>>>> REPLACE
  ```
  
  Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
  Wrap the *SEARCH/REPLACE* edit in blocks ```python...```.
  
messages.role: user
verification_info: {"file_context": {"src/marshmallow/schema.py": "# -*- coding: utf-8 -*-\n\"\"\"The :class:`Schema` class, including its metaclass and options (class Meta).\"\"\"\nfrom __future__ import absolute_import, unicode_literals\n\nfrom collections import defaultdict, namedtuple\nimport copy\nimport datetime as dt\nimport decimal\nimport inspect\nimport json\nimport uuid\nimport warnings\nimport functools\n\nfrom marshmallow import base, fields, utils, class_registry, marshalling\nfrom marshmallow.compat import (with_metaclass, iteritems, text_type,\n                                binary_type, Mapping, OrderedDict)\nfrom marshmallow.exceptions import ValidationError\nfrom marshmallow.orderedset import OrderedSet\nfrom marshmallow.decorators import (PRE_DUMP, POST_DUMP, PRE_LOAD, POST_LOAD,\n                                    VALIDATES, VALIDATES_SCHEMA)\nfrom marshmallow.utils import missing\nfrom marshmallow.warnings import RemovedInMarshmallow3Warning, ChangedInMarshmallow3Warning\n\n\n#: Return type of :meth:`Schema.dump` including serialized data and errors\nMarshalResult = namedtuple('MarshalResult', ['data', 'errors'])\n#: Return type of :meth:`Schema.load`, including deserialized data and errors\nUnmarshalResult = namedtuple('UnmarshalResult', ['data', 'errors'])\n\ndef _get_fields(attrs, field_class, pop=False, ordered=False):\n    \"\"\"Get fields from a class. If ordered=True, fields will sorted by creation index.\n\n    :param attrs: Mapping of class attributes\n    :param type field_class: Base field class\n    :param bool pop: Remove matching fields\n    \"\"\"\n    getter = getattr(attrs, 'pop' if pop else 'get')\n    fields = [\n        (field_name, getter(field_name))\n        for field_name, field_value in list(iteritems(attrs))\n        if utils.is_instance_or_subclass(field_value, field_class)\n    ]\n    if ordered:\n        return sorted(\n            fields,\n            key=lambda pair: pair[1]._creation_index,\n        )\n    else:\n        return fields\n\n# This function allows Schemas to inherit from non-Schema classes and ensures\n#   inheritance according to the MRO\ndef _get_fields_by_mro(klass, field_class, ordered=False):\n    \"\"\"Collect fields from a class, following its method resolution order. The\n    class itself is excluded from the search; only its parents are checked. Get\n    fields from ``_declared_fields`` if available, else use ``__dict__``.\n\n    :param type klass: Class whose fields to retrieve\n    :param type field_class: Base field class\n    \"\"\"\n    mro = inspect.getmro(klass)\n    # Loop over mro in reverse to maintain correct order of fields\n    return sum(\n        (\n            _get_fields(\n                getattr(base, '_declared_fields', base.__dict__),\n                field_class,\n                ordered=ordered\n            )\n            for base in mro[:0:-1]\n        ),\n        [],\n    )\n\n\nclass SchemaMeta(type):\n    \"\"\"Metaclass for the Schema class. Binds the declared fields to\n    a ``_declared_fields`` attribute, which is a dictionary mapping attribute\n    names to field objects. Also sets the ``opts`` class attribute, which is\n    the Schema class's ``class Meta`` options.\n    \"\"\"\n\n    def __new__(mcs, name, bases, attrs):\n        meta = attrs.get('Meta')\n        ordered = getattr(meta, 'ordered', False)\n        if not ordered:\n            # Inherit 'ordered' option\n            # Warning: We loop through bases instead of MRO because we don't\n            # yet have access to the class object\n            # (i.e. can't call super before we have fields)\n            for base_ in bases:\n                if hasattr(base_, 'Meta') and hasattr(base_.Meta, 'ordered'):\n                    ordered = base_.Meta.ordered\n                    break\n            else:\n                ordered = False\n        cls_fields = _get_fields(attrs, base.FieldABC, pop=True, ordered=ordered)\n        klass = super(SchemaMeta, mcs).__new__(mcs, name, bases, attrs)\n        inherited_fields = _get_fields_by_mro(klass, base.FieldABC, ordered=ordered)\n\n        # Use getattr rather than attrs['Meta'] so that we get inheritance for free\n        meta = getattr(klass, 'Meta')\n        # Set klass.opts in __new__ rather than __init__ so that it is accessible in\n        # get_declared_fields\n        klass.opts = klass.OPTIONS_CLASS(meta)\n        # Pass the inherited `ordered` into opts\n        klass.opts.ordered = ordered\n        # Add fields specifid in the `include` class Meta option\n        cls_fields += list(klass.opts.include.items())\n\n        dict_cls = OrderedDict if ordered else dict\n        # Assign _declared_fields on class\n        klass._declared_fields = mcs.get_declared_fields(\n            klass=klass,\n            cls_fields=cls_fields,\n            inherited_fields=inherited_fields,\n            dict_cls=dict_cls\n        )\n        return klass\n\n    @classmethod\n    def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls):\n        \"\"\"Returns a dictionary of field_name => `Field` pairs declard on the class.\n        This is exposed mainly so that plugins can add additional fields, e.g. fields\n        computed from class Meta options.\n\n        :param type klass: The class object.\n        :param dict cls_fields: The fields declared on the class, including those added\n            by the ``include`` class Meta option.\n        :param dict inherited_fileds: Inherited fields.\n        :param type dict_class: Either `dict` or `OrderedDict`, depending on the whether\n            the user specified `ordered=True`.\n        \"\"\"\n        return dict_cls(inherited_fields + cls_fields)\n\n    # NOTE: self is the class object\n    def __init__(self, name, bases, attrs):\n        super(SchemaMeta, self).__init__(name, bases, attrs)\n        if name:\n            class_registry.register(name, self)\n        self._resolve_processors()\n\n    def _resolve_processors(self):\n        \"\"\"Add in the decorated processors\n\n        By doing this after constructing the class, we let standard inheritance\n        do all the hard work.\n        \"\"\"\n        mro = inspect.getmro(self)\n        self._has_processors = False\n        self.__processors__ = defaultdict(list)\n        for attr_name in dir(self):\n            # Need to look up the actual descriptor, not whatever might be\n            # bound to the class. This needs to come from the __dict__ of the\n            # declaring class.\n            for parent in mro:\n                try:\n                    attr = parent.__dict__[attr_name]\n                except KeyError:\n                    continue\n                else:\n                    break\n            else:\n                # In case we didn't find the attribute and didn't break above.\n                # We should never hit this - it's just here for completeness\n                # to exclude the possibility of attr being undefined.\n                continue\n\n            try:\n                processor_tags = attr.__marshmallow_tags__\n            except AttributeError:\n                continue\n\n            self._has_processors = bool(processor_tags)\n            for tag in processor_tags:\n                # Use name here so we can get the bound method later, in case\n                # the processor was a descriptor or something.\n                self.__processors__[tag].append(attr_name)\n\n\nclass SchemaOpts(object):\n    \"\"\"class Meta options for the :class:`Schema`. Defines defaults.\"\"\"\n\n    def __init__(self, meta):\n        self.fields = getattr(meta, 'fields', ())\n        if not isinstance(self.fields, (list, tuple)):\n            raise ValueError(\"`fields` option must be a list or tuple.\")\n        self.additional = getattr(meta, 'additional', ())\n        if not isinstance(self.additional, (list, tuple)):\n            raise ValueError(\"`additional` option must be a list or tuple.\")\n        if self.fields and self.additional:\n            raise ValueError(\"Cannot set both `fields` and `additional` options\"\n                            \" for the same Schema.\")\n        self.exclude = getattr(meta, 'exclude', ())\n        if not isinstance(self.exclude, (list, tuple)):\n            raise ValueError(\"`exclude` must be a list or tuple.\")\n        self.strict = getattr(meta, 'strict', False)\n        if hasattr(meta, 'dateformat'):\n            warnings.warn(\n                \"The dateformat option is renamed to datetimeformat in marshmallow 3.\",\n                ChangedInMarshmallow3Warning\n            )\n        self.dateformat = getattr(meta, 'dateformat', None)\n        if hasattr(meta, 'json_module'):\n            warnings.warn(\n                \"The json_module option is renamed to render_module in marshmallow 3.\",\n                ChangedInMarshmallow3Warning\n            )\n        self.json_module = getattr(meta, 'json_module', json)\n        if hasattr(meta, 'skip_missing'):\n            warnings.warn(\n                'The skip_missing option is no longer necessary. Missing inputs passed to '\n                'Schema.dump will be excluded from the serialized output by default.',\n                UserWarning\n            )\n        self.ordered = getattr(meta, 'ordered', False)\n        self.index_errors = getattr(meta, 'index_errors', True)\n        self.include = getattr(meta, 'include', {})\n        self.load_only = getattr(meta, 'load_only', ())\n        self.dump_only = getattr(meta, 'dump_only', ())\n\n\nclass BaseSchema(base.SchemaABC):\n    \"\"\"Base schema class with which to define custom schemas.\n\n    Example usage:\n\n    .. code-block:: python\n\n        import datetime as dt\n        from marshmallow import Schema, fields\n\n        class Album(object):\n            def __init__(self, title, release_date):\n                self.title = title\n                self.release_date = release_date\n\n        class AlbumSchema(Schema):\n            title = fields.Str()\n            release_date = fields.Date()\n\n        # Or, equivalently\n        class AlbumSchema2(Schema):\n            class Meta:\n                fields = (\"title\", \"release_date\")\n\n        album = Album(\"Beggars Banquet\", dt.date(1968, 12, 6))\n        schema = AlbumSchema()\n        data, errors = schema.dump(album)\n        data  # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'}\n\n    :param dict extra: A dict of extra attributes to bind to the serialized result.\n    :param tuple|list only: Whitelist of fields to select when instantiating the Schema.\n        If None, all fields are used.\n        Nested fields can be represented with dot delimiters.\n    :param tuple|list exclude: Blacklist of fields to exclude when instantiating the Schema.\n        If a field appears in both `only` and `exclude`, it is not used.\n        Nested fields can be represented with dot delimiters.\n    :param str prefix: Optional prefix that will be prepended to all the\n        serialized field names.\n    :param bool strict: If `True`, raise errors if invalid data are passed in\n        instead of failing silently and storing the errors.\n    :param bool many: Should be set to `True` if ``obj`` is a collection\n        so that the object will be serialized to a list.\n    :param dict context: Optional context passed to :class:`fields.Method` and\n        :class:`fields.Function` fields.\n    :param tuple|list load_only: Fields to skip during serialization (write-only fields)\n    :param tuple|list dump_only: Fields to skip during deserialization (read-only fields)\n    :param bool|tuple partial: Whether to ignore missing fields. If its value\n        is an iterable, only missing fields listed in that iterable will be\n        ignored.\n\n    .. versionchanged:: 2.0.0\n        `__validators__`, `__preprocessors__`, and `__data_handlers__` are removed in favor of\n        `marshmallow.decorators.validates_schema`,\n        `marshmallow.decorators.pre_load` and `marshmallow.decorators.post_dump`.\n        `__accessor__` and `__error_handler__` are deprecated. Implement the\n        `handle_error` and `get_attribute` methods instead.\n        \"\"\"\n    TYPE_MAPPING = {\n        text_type: fields.String,\n        binary_type: fields.String,\n        dt.datetime: fields.DateTime,\n        float: fields.Float,\n        bool: fields.Boolean,\n        tuple: fields.Raw,\n        list: fields.Raw,\n        set: fields.Raw,\n        int: fields.Integer,\n        uuid.UUID: fields.UUID,\n        dt.time: fields.Time,\n        dt.date: fields.Date,\n        dt.timedelta: fields.TimeDelta,\n        decimal.Decimal: fields.Decimal,\n    }\n\n    OPTIONS_CLASS = SchemaOpts\n\n    #: DEPRECATED: Custom error handler function. May be `None`.\n    __error_handler__ = None\n    #: DEPRECATED: Function used to get values of an object.\n    __accessor__ = None\n\n    class Meta(object):\n        \"\"\"Options object for a Schema.\n\n        Example usage: ::\n\n            class Meta:\n                fields = (\"id\", \"email\", \"date_created\")\n                exclude = (\"password\", \"secret_attribute\")\n\n        Available options:\n\n        - ``fields``: Tuple or list of fields to include in the serialized result.\n        - ``additional``: Tuple or list of fields to include *in addition* to the\n            explicitly declared fields. ``additional`` and ``fields`` are\n            mutually-exclusive options.\n        - ``include``: Dictionary of additional fields to include in the schema. It is\n            usually better to define fields as class variables, but you may need to\n            use this option, e.g., if your fields are Python keywords. May be an\n            `OrderedDict`.\n        - ``exclude``: Tuple or list of fields to exclude in the serialized result.\n            Nested fields can be represented with dot delimiters.\n        - ``dateformat``: Date format for all DateTime fields that do not have their\n            date format explicitly specified.\n        - ``strict``: If `True`, raise errors during marshalling rather than\n            storing them.\n        - ``json_module``: JSON module to use for `loads` and `dumps`.\n            Defaults to the ``json`` module in the stdlib.\n        - ``ordered``: If `True`, order serialization output according to the\n            order in which fields were declared. Output of `Schema.dump` will be a\n            `collections.OrderedDict`.\n        - ``index_errors``: If `True`, errors dictionaries will include the index\n            of invalid items in a collection.\n        - ``load_only``: Tuple or list of fields to exclude from serialized results.\n        - ``dump_only``: Tuple or list of fields to exclude from deserialization\n        \"\"\"\n        pass\n\n    def __init__(self, extra=None, only=None, exclude=(), prefix='', strict=None,\n                 many=False, context=None, load_only=(), dump_only=(),\n                 partial=False):\n        # copy declared fields from metaclass\n        self.declared_fields = copy.deepcopy(self._declared_fields)\n        self.many = many\n        self.only = only\n        self.exclude = set(self.opts.exclude) | set(exclude)\n        if prefix:\n            warnings.warn(\n                'The `prefix` argument is deprecated. Use a post_dump '\n                'method to insert a prefix instead.',\n                RemovedInMarshmallow3Warning\n            )\n        self.prefix = prefix\n        self.strict = strict if strict is not None else self.opts.strict\n        self.ordered = self.opts.ordered\n        self.load_only = set(load_only) or set(self.opts.load_only)\n        self.dump_only = set(dump_only) or set(self.opts.dump_only)\n        self.partial = partial\n        #: Dictionary mapping field_names -> :class:`Field` objects\n        self.fields = self.dict_class()\n        if extra:\n            warnings.warn(\n                'The `extra` argument is deprecated. Use a post_dump '\n                'method to add additional data instead.',\n                RemovedInMarshmallow3Warning\n            )\n        self.extra = extra\n        self.context = context or {}\n        self._normalize_nested_options()\n        self._types_seen = set()\n        self._update_fields(many=many)\n\n    def __repr__(self):\n        return '<{ClassName}(many={self.many}, strict={self.strict})>'.format(\n            ClassName=self.__class__.__name__, self=self\n        )\n\n    def _postprocess(self, data, many, obj):\n        if self.extra:\n            if many:\n                for each in data:\n                    each.update(self.extra)\n            else:\n                data.update(self.extra)\n        return data\n\n    @property\n    def dict_class(self):\n        return OrderedDict if self.ordered else dict\n\n    @property\n    def set_class(self):\n        return OrderedSet if self.ordered else set\n\n    ##### Override-able methods #####\n\n    def handle_error(self, error, data):\n        \"\"\"Custom error handler function for the schema.\n\n        :param ValidationError error: The `ValidationError` raised during (de)serialization.\n        :param data: The original input data.\n\n        .. versionadded:: 2.0.0\n        \"\"\"\n        pass\n\n    def get_attribute(self, attr, obj, default):\n        \"\"\"Defines how to pull values from an object to serialize.\n\n        .. versionadded:: 2.0.0\n        \"\"\"\n        return utils.get_value(attr, obj, default)\n\n    ##### Handler decorators (deprecated) #####\n\n    @classmethod\n    def error_handler(cls, func):\n        \"\"\"Decorator that registers an error handler function for the schema.\n        The function receives the :class:`Schema` instance, a dictionary of errors,\n        and the serialized object (if serializing data) or data dictionary (if\n        deserializing data) as arguments.\n\n        Example: ::\n\n            class UserSchema(Schema):\n                email = fields.Email()\n\n            @UserSchema.error_handler\n            def handle_errors(schema, errors, obj):\n                raise ValueError('An error occurred while marshalling {}'.format(obj))\n\n            user = User(email='invalid')\n            UserSchema().dump(user)  # => raises ValueError\n            UserSchema().load({'email': 'bademail'})  # raises ValueError\n\n        .. versionadded:: 0.7.0\n        .. deprecated:: 2.0.0\n            Set the ``error_handler`` class Meta option instead.\n        \"\"\"\n        warnings.warn(\n            'Schema.error_handler is deprecated. Set the error_handler class Meta option '\n            'instead.', category=DeprecationWarning\n        )\n        cls.__error_handler__ = func\n        return func\n\n    @classmethod\n    def accessor(cls, func):\n        \"\"\"Decorator that registers a function for pulling values from an object\n        to serialize. The function receives the :class:`Schema` instance, the\n        ``key`` of the value to get, the ``obj`` to serialize, and an optional\n        ``default`` value.\n\n        .. deprecated:: 2.0.0\n            Set the ``error_handler`` class Meta option instead.\n        \"\"\"\n        warnings.warn(\n            'Schema.accessor is deprecated. Set the accessor class Meta option '\n            'instead.', category=DeprecationWarning\n        )\n        cls.__accessor__ = func\n        return func\n\n    ##### Serialization/Deserialization API #####\n\n    def dump(self, obj, many=None, update_fields=True, **kwargs):\n        \"\"\"Serialize an object to native Python data types according to this\n        Schema's fields.\n\n        :param obj: The object to serialize.\n        :param bool many: Whether to serialize `obj` as a collection. If `None`, the value\n            for `self.many` is used.\n        :param bool update_fields: Whether to update the schema's field classes. Typically\n            set to `True`, but may be `False` when serializing a homogenous collection.\n            This parameter is used by `fields.Nested` to avoid multiple updates.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `MarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        # Callable marshalling object\n        marshal = marshalling.Marshaller(prefix=self.prefix)\n        errors = {}\n        many = self.many if many is None else bool(many)\n        if many and utils.is_iterable_but_not_string(obj):\n            obj = list(obj)\n\n        if self._has_processors:\n            try:\n                processed_obj = self._invoke_dump_processors(\n                    PRE_DUMP,\n                    obj,\n                    many,\n                    original_data=obj)\n            except ValidationError as error:\n                errors = error.normalized_messages()\n                result = None\n        else:\n            processed_obj = obj\n\n        if not errors:\n            if update_fields:\n                obj_type = type(processed_obj)\n                if obj_type not in self._types_seen:\n                    self._update_fields(processed_obj, many=many)\n                    if not isinstance(processed_obj, Mapping):\n                        self._types_seen.add(obj_type)\n\n            try:\n                preresult = marshal(\n                    processed_obj,\n                    self.fields,\n                    many=many,\n                    # TODO: Remove self.__accessor__ in a later release\n                    accessor=self.get_attribute or self.__accessor__,\n                    dict_class=self.dict_class,\n                    index_errors=self.opts.index_errors,\n                    **kwargs\n                )\n            except ValidationError as error:\n                errors = marshal.errors\n                preresult = error.data\n\n            result = self._postprocess(preresult, many, obj=obj)\n\n        if not errors and self._has_processors:\n            try:\n                result = self._invoke_dump_processors(\n                    POST_DUMP,\n                    result,\n                    many,\n                    original_data=obj)\n            except ValidationError as error:\n                errors = error.normalized_messages()\n        if errors:\n            # TODO: Remove self.__error_handler__ in a later release\n            if self.__error_handler__ and callable(self.__error_handler__):\n                self.__error_handler__(errors, obj)\n            exc = ValidationError(\n                errors,\n                field_names=marshal.error_field_names,\n                fields=marshal.error_fields,\n                data=obj,\n                **marshal.error_kwargs\n            )\n            self.handle_error(exc, obj)\n            if self.strict:\n                raise exc\n\n        return MarshalResult(result, errors)\n\n    def dumps(self, obj, many=None, update_fields=True, *args, **kwargs):\n        \"\"\"Same as :meth:`dump`, except return a JSON-encoded string.\n\n        :param obj: The object to serialize.\n        :param bool many: Whether to serialize `obj` as a collection. If `None`, the value\n            for `self.many` is used.\n        :param bool update_fields: Whether to update the schema's field classes. Typically\n            set to `True`, but may be `False` when serializing a homogenous collection.\n            This parameter is used by `fields.Nested` to avoid multiple updates.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `MarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        deserialized, errors = self.dump(obj, many=many, update_fields=update_fields)\n        ret = self.opts.json_module.dumps(deserialized, *args, **kwargs)\n        return MarshalResult(ret, errors)\n\n    def load(self, data, many=None, partial=None):\n        \"\"\"Deserialize a data structure to an object defined by this Schema's\n        fields and :meth:`make_object`.\n\n        :param dict data: The data to deserialize.\n        :param bool many: Whether to deserialize `data` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to ignore missing fields. If `None`,\n            the value for `self.partial` is used. If its value is an iterable,\n            only missing fields listed in that iterable will be ignored.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `UnmarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        result, errors = self._do_load(data, many, partial=partial, postprocess=True)\n        return UnmarshalResult(data=result, errors=errors)\n\n    def loads(self, json_data, many=None, *args, **kwargs):\n        \"\"\"Same as :meth:`load`, except it takes a JSON string as input.\n\n        :param str json_data: A JSON string of the data to deserialize.\n        :param bool many: Whether to deserialize `obj` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to ignore missing fields. If `None`,\n            the value for `self.partial` is used. If its value is an iterable,\n            only missing fields listed in that iterable will be ignored.\n        :return: A tuple of the form (``data``, ``errors``)\n        :rtype: `UnmarshalResult`, a `collections.namedtuple`\n\n        .. versionadded:: 1.0.0\n        \"\"\"\n        # TODO: This avoids breaking backward compatibility if people were\n        # passing in positional args after `many` for use by `json.loads`, but\n        # ideally we shouldn't have to do this.\n        partial = kwargs.pop('partial', None)\n\n        data = self.opts.json_module.loads(json_data, *args, **kwargs)\n        return self.load(data, many=many, partial=partial)\n\n    def validate(self, data, many=None, partial=None):\n        \"\"\"Validate `data` against the schema, returning a dictionary of\n        validation errors.\n\n        :param dict data: The data to validate.\n        :param bool many: Whether to validate `data` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to ignore missing fields. If `None`,\n            the value for `self.partial` is used. If its value is an iterable,\n            only missing fields listed in that iterable will be ignored.\n        :return: A dictionary of validation errors.\n        :rtype: dict\n\n        .. versionadded:: 1.1.0\n        \"\"\"\n        _, errors = self._do_load(data, many, partial=partial, postprocess=False)\n        return errors\n\n    ##### Private Helpers #####\n\n    def _do_load(self, data, many=None, partial=None, postprocess=True):\n        \"\"\"Deserialize `data`, returning the deserialized result and a dictonary of\n        validation errors.\n\n        :param data: The data to deserialize.\n        :param bool many: Whether to deserialize `data` as a collection. If `None`, the\n            value for `self.many` is used.\n        :param bool|tuple partial: Whether to validate required fields. If its value is an iterable,\n            only fields listed in that iterable will be ignored will be allowed missing.\n            If `True`, all fields will be allowed missing.\n            If `None`, the value for `self.partial` is used.\n        :param bool postprocess: Whether to run post_load methods..\n        :return: A tuple of the form (`data`, `errors`)\n        \"\"\"\n        # Callable unmarshalling object\n        unmarshal = marshalling.Unmarshaller()\n        errors = {}\n        many = self.many if many is None else bool(many)\n        if partial is None:\n            partial = self.partial\n        try:\n            processed_data = self._invoke_load_processors(\n                PRE_LOAD,\n                data,\n                many,\n                original_data=data)\n        except ValidationError as err:\n            errors = err.normalized_messages()\n            result = None\n        if not errors:\n            try:\n                result = unmarshal(\n                    processed_data,\n                    self.fields,\n                    many=many,\n                    partial=partial,\n                    dict_class=self.dict_class,\n                    index_errors=self.opts.index_errors,\n                )\n            except ValidationError as error:\n                result = error.data\n            self._invoke_field_validators(unmarshal, data=result, many=many)\n            errors = unmarshal.errors\n            field_errors = bool(errors)\n            # Run schema-level migration\n            try:\n                self._invoke_validators(unmarshal, pass_many=True, data=result, original_data=data,\n                                        many=many, field_errors=field_errors)\n            except ValidationError as err:\n                errors.update(err.messages)\n            try:\n                self._invoke_validators(unmarshal, pass_many=False, data=result, original_data=data,\n                                        many=many, field_errors=field_errors)\n            except ValidationError as err:\n                errors.update(err.messages)\n        # Run post processors\n        if not errors and postprocess:\n            try:\n                result = self._invoke_load_processors(\n                    POST_LOAD,\n                    result,\n                    many,\n                    original_data=data)\n            except ValidationError as err:\n                errors = err.normalized_messages()\n        if errors:\n            # TODO: Remove self.__error_handler__ in a later release\n            if self.__error_handler__ and callable(self.__error_handler__):\n                self.__error_handler__(errors, data)\n            exc = ValidationError(\n                errors,\n                field_names=unmarshal.error_field_names,\n                fields=unmarshal.error_fields,\n                data=data,\n                **unmarshal.error_kwargs\n            )\n            self.handle_error(exc, data)\n            if self.strict:\n                raise exc\n\n        return result, errors\n\n    def _normalize_nested_options(self):\n        \"\"\"Apply then flatten nested schema options\"\"\"\n        if self.only is not None:\n            # Apply the only option to nested fields.\n            self.__apply_nested_option('only', self.only, 'intersection')\n            # Remove the child field names from the only option.\n            self.only = self.set_class(\n                [field.split('.', 1)[0] for field in self.only],\n            )\n        if self.exclude:\n            # Apply the exclude option to nested fields.\n            self.__apply_nested_option('exclude', self.exclude, 'union')\n            # Remove the parent field names from the exclude option.\n            self.exclude = self.set_class(\n                [field for field in self.exclude if '.' not in field],\n            )\n\n    def __apply_nested_option(self, option_name, field_names, set_operation):\n        \"\"\"Apply nested options to nested fields\"\"\"\n        # Split nested field names on the first dot.\n        nested_fields = [name.split('.', 1) for name in field_names if '.' in name]\n        # Partition the nested field names by parent field.\n        nested_options = defaultdict(list)\n        for parent, nested_names in nested_fields:\n            nested_options[parent].append(nested_names)\n        # Apply the nested field options.\n        for key, options in iter(nested_options.items()):\n            new_options = self.set_class(options)\n            original_options = getattr(self.declared_fields[key], option_name, ())\n            if original_options:\n                if set_operation == 'union':\n                    new_options |= self.set_class(original_options)\n                if set_operation == 'intersection':\n                    new_options &= self.set_class(original_options)\n            setattr(self.declared_fields[key], option_name, new_options)\n\n    def _update_fields(self, obj=None, many=False):\n        \"\"\"Update fields based on the passed in object.\"\"\"\n        if self.only is not None:\n            # Return only fields specified in only option\n            if self.opts.fields:\n                field_names = self.set_class(self.opts.fields) & self.set_class(self.only)\n            else:\n                field_names = self.set_class(self.only)\n        elif self.opts.fields:\n            # Return fields specified in fields option\n            field_names = self.set_class(self.opts.fields)\n        elif self.opts.additional:\n            # Return declared fields + additional fields\n            field_names = (self.set_class(self.declared_fields.keys()) |\n                            self.set_class(self.opts.additional))\n        else:\n            field_names = self.set_class(self.declared_fields.keys())\n\n        # If \"exclude\" option or param is specified, remove those fields\n        field_names -= self.exclude\n        ret = self.__filter_fields(field_names, obj, many=many)\n        # Set parents\n        self.__set_field_attrs(ret)\n        self.fields = ret\n        return self.fields\n\n    def on_bind_field(self, field_name, field_obj):\n        \"\"\"Hook to modify a field when it is bound to the `Schema`. No-op by default.\"\"\"\n        return None\n\n    def __set_field_attrs(self, fields_dict):\n        \"\"\"Bind fields to the schema, setting any necessary attributes\n        on the fields (e.g. parent and name).\n\n        Also set field load_only and dump_only values if field_name was\n        specified in ``class Meta``.\n        \"\"\"\n        for field_name, field_obj in iteritems(fields_dict):\n            try:\n                if field_name in self.load_only:\n                    field_obj.load_only = True\n                if field_name in self.dump_only:\n                    field_obj.dump_only = True\n                field_obj._add_to_schema(field_name, self)\n                self.on_bind_field(field_name, field_obj)\n            except TypeError:\n                # field declared as a class, not an instance\n                if (isinstance(field_obj, type) and\n                        issubclass(field_obj, base.FieldABC)):\n                    msg = ('Field for \"{0}\" must be declared as a '\n                           'Field instance, not a class. '\n                           'Did you mean \"fields.{1}()\"?'\n                           .format(field_name, field_obj.__name__))\n                    raise TypeError(msg)\n        return fields_dict\n\n    def __filter_fields(self, field_names, obj, many=False):\n        \"\"\"Return only those field_name:field_obj pairs specified by\n        ``field_names``.\n\n        :param set field_names: Field names to include in the final\n            return dictionary.\n        :param object|Mapping|list obj The object to base filtered fields on.\n        :returns: An dict of field_name:field_obj pairs.\n        \"\"\"\n        if obj and many:\n            try:  # list\n                obj = obj[0]\n            except IndexError:  # Nothing to serialize\n                return dict((k, v) for k, v in self.declared_fields.items() if k in field_names)\n        ret = self.dict_class()\n        for key in field_names:\n            if key in self.declared_fields:\n                ret[key] = self.declared_fields[key]\n            else:  # Implicit field creation (class Meta 'fields' or 'additional')\n                if obj:\n                    attribute_type = None\n                    try:\n                        if isinstance(obj, Mapping):\n                            attribute_type = type(obj[key])\n                        else:\n                            attribute_type = type(getattr(obj, key))\n                    except (AttributeError, KeyError) as err:\n                        err_type = type(err)\n                        raise err_type(\n                            '\"{0}\" is not a valid field for {1}.'.format(key, obj))\n                    field_obj = self.TYPE_MAPPING.get(attribute_type, fields.Field)()\n                else:  # Object is None\n                    field_obj = fields.Field()\n                # map key -> field (default to Raw)\n                ret[key] = field_obj\n        return ret\n\n    def _invoke_dump_processors(self, tag_name, data, many, original_data=None):\n        # The pass_many post-dump processors may do things like add an envelope, so\n        # invoke those after invoking the non-pass_many processors which will expect\n        # to get a list of items.\n        data = self._invoke_processors(tag_name, pass_many=False,\n            data=data, many=many, original_data=original_data)\n        data = self._invoke_processors(tag_name, pass_many=True,\n            data=data, many=many, original_data=original_data)\n        return data\n\n    def _invoke_load_processors(self, tag_name, data, many, original_data=None):\n        # This has to invert the order of the dump processors, so run the pass_many\n        # processors first.\n        data = self._invoke_processors(tag_name, pass_many=True,\n            data=data, many=many, original_data=original_data)\n        data = self._invoke_processors(tag_name, pass_many=False,\n            data=data, many=many, original_data=original_data)\n        return data\n\n    def _invoke_field_validators(self, unmarshal, data, many):\n        for attr_name in self.__processors__[(VALIDATES, False)]:\n            validator = getattr(self, attr_name)\n            validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATES, False)]\n            field_name = validator_kwargs['field_name']\n\n            try:\n                field_obj = self.fields[field_name]\n            except KeyError:\n                if field_name in self.declared_fields:\n                    continue\n                raise ValueError('\"{0}\" field does not exist.'.format(field_name))\n\n            if many:\n                for idx, item in enumerate(data):\n                    try:\n                        value = item[field_obj.attribute or field_name]\n                    except KeyError:\n                        pass\n                    else:\n                        validated_value = unmarshal.call_and_store(\n                            getter_func=validator,\n                            data=value,\n                            field_name=field_obj.load_from or field_name,\n                            field_obj=field_obj,\n                            index=(idx if self.opts.index_errors else None)\n                        )\n                        if validated_value is missing:\n                            data[idx].pop(field_name, None)\n            else:\n                try:\n                    value = data[field_obj.attribute or field_name]\n                except KeyError:\n                    pass\n                else:\n                    validated_value = unmarshal.call_and_store(\n                        getter_func=validator,\n                        data=value,\n                        field_name=field_obj.load_from or field_name,\n                        field_obj=field_obj\n                    )\n                    if validated_value is missing:\n                        data.pop(field_name, None)\n\n    def _invoke_validators(\n            self, unmarshal, pass_many, data, original_data, many, field_errors=False):\n        errors = {}\n        for attr_name in self.__processors__[(VALIDATES_SCHEMA, pass_many)]:\n            validator = getattr(self, attr_name)\n            validator_kwargs = validator.__marshmallow_kwargs__[(VALIDATES_SCHEMA, pass_many)]\n            pass_original = validator_kwargs.get('pass_original', False)\n\n            skip_on_field_errors = validator_kwargs['skip_on_field_errors']\n            if skip_on_field_errors and field_errors:\n                continue\n\n            if pass_many:\n                validator = functools.partial(validator, many=many)\n            if many and not pass_many:\n                for idx, item in enumerate(data):\n                    try:\n                        unmarshal.run_validator(validator,\n                                                item, original_data, self.fields, many=many,\n                                                index=idx, pass_original=pass_original)\n                    except ValidationError as err:\n                        errors.update(err.messages)\n            else:\n                try:\n                    unmarshal.run_validator(validator,\n                                            data, original_data, self.fields, many=many,\n                                            pass_original=pass_original)\n                except ValidationError as err:\n                    errors.update(err.messages)\n        if errors:\n            raise ValidationError(errors)\n        return None\n\n    def _invoke_processors(self, tag_name, pass_many, data, many, original_data=None):\n        for attr_name in self.__processors__[(tag_name, pass_many)]:\n            # This will be a bound method.\n            processor = getattr(self, attr_name)\n\n            processor_kwargs = processor.__marshmallow_kwargs__[(tag_name, pass_many)]\n            pass_original = processor_kwargs.get('pass_original', False)\n\n            if pass_many:\n                if pass_original:\n                    data = utils.if_none(processor(data, many, original_data), data)\n                else:\n                    data = utils.if_none(processor(data, many), data)\n            elif many:\n                if pass_original:\n                    data = [utils.if_none(processor(item, original_data), item)\n                            for item in data]\n                else:\n                    data = [utils.if_none(processor(item), item) for item in data]\n            else:\n                if pass_original:\n                    data = utils.if_none(processor(data, original_data), data)\n                else:\n                    data = utils.if_none(processor(data), data)\n        return data\n\n\nclass Schema(with_metaclass(SchemaMeta, BaseSchema)):\n    __doc__ = BaseSchema.__doc__\n"}, "filelevel_patches": {"src/marshmallow/schema.py": "@@ -877,7 +877,7 @@ def _invoke_field_validators(self, unmarshal, data, many):\n                 for idx, item in enumerate(data):\n                     try:\n                         value = item[field_obj.attribute or field_name]\n-                    except KeyError:\n+                    except (KeyError, TypeError):\n                         pass\n                     else:\n                         validated_value = unmarshal.call_and_store(\n@@ -892,7 +892,7 @@ def _invoke_field_validators(self, unmarshal, data, many):\n             else:\n                 try:\n                     value = data[field_obj.attribute or field_name]\n-                except KeyError:\n+                except (KeyError, TypeError):\n                     pass\n                 else:\n                     validated_value = unmarshal.call_and_store("}}