--- utils ---
"""Utility methods for marshmallow."""
from __future__ import annotations
import collections
import datetime as dt
import functools
import inspect
import json
import re
import typing
import warnings
from collections.abc import Mapping
from email.utils import format_datetime, parsedate_to_datetime
from pprint import pprint as py_pprint
from marshmallow.base import FieldABC
from marshmallow.exceptions import FieldInstanceResolutionError
from marshmallow.warnings import RemovedInMarshmallow4Warning
EXCLUDE = 'exclude'
INCLUDE = 'include'
RAISE = 'raise'
_UNKNOWN_VALUES = {EXCLUDE, INCLUDE, RAISE}

class _Missing:

    def __bool__(self):
        return False

    def __copy__(self):
        return self

    def __deepcopy__(self, _):
        return self

    def __repr__(self):
        return '<marshmallow.missing>'
missing = _Missing()

def is_generator(obj) -> bool:
    """Return True if ``obj`` is a generator"""
    pass

def is_iterable_but_not_string(obj) -> bool:
    """Return True if ``obj`` is an iterable object that isn't a string."""
    pass

def is_collection(obj) -> bool:
    """Return True if ``obj`` is a collection type, e.g list, tuple, queryset."""
    pass

def is_instance_or_subclass(val, class_) -> bool:
    """Return True if ``val`` is either a subclass or instance of ``class_``."""
    pass

def is_keyed_tuple(obj) -> bool:
    """Return True if ``obj`` has keyed tuple behavior, such as
    namedtuples or SQLAlchemy's KeyedTuples.
    """
    pass

def pprint(obj, *args, **kwargs) -> None:
    """Pretty-printing function that can pretty-print OrderedDicts
    like regular dictionaries. Useful for printing the output of
    :meth:`marshmallow.Schema.dump`.

    .. deprecated:: 3.7.0
        marshmallow.pprint will be removed in marshmallow 4.
    """
    pass

def from_rfc(datestring: str) -> dt.datetime:
    """Parse a RFC822-formatted datetime string and return a datetime object.

    https://stackoverflow.com/questions/885015/how-to-parse-a-rfc-2822-date-time-into-a-python-datetime  # noqa: B950
    """
    pass

def rfcformat(datetime: dt.datetime) -> str:
    """Return the RFC822-formatted representation of a datetime object.

    :param datetime datetime: The datetime.
    """
    pass
_iso8601_datetime_re = re.compile('(?P<year>\\d{4})-(?P<month>\\d{1,2})-(?P<day>\\d{1,2})[T ](?P<hour>\\d{1,2}):(?P<minute>\\d{1,2})(?::(?P<second>\\d{1,2})(?:\\.(?P<microsecond>\\d{1,6})\\d{0,6})?)?(?P<tzinfo>Z|[+-]\\d{2}(?::?\\d{2})?)?$')
_iso8601_date_re = re.compile('(?P<year>\\d{4})-(?P<month>\\d{1,2})-(?P<day>\\d{1,2})$')
_iso8601_time_re = re.compile('(?P<hour>\\d{1,2}):(?P<minute>\\d{1,2})(?::(?P<second>\\d{1,2})(?:\\.(?P<microsecond>\\d{1,6})\\d{0,6})?)?')

def get_fixed_timezone(offset: int | float | dt.timedelta) -> dt.timezone:
    """Return a tzinfo instance with a fixed offset from UTC."""
    pass

def from_iso_datetime(value):
    """Parse a string and return a datetime.datetime.

    This function supports time zone offsets. When the input contains one,
    the output uses a timezone with a fixed offset from UTC.
    """
    pass

def from_iso_time(value):
    """Parse a string and return a datetime.time.

    This function doesn't support time zone offsets.
    """
    pass

def from_iso_date(value):
    """Parse a string and return a datetime.date."""
    pass

def isoformat(datetime: dt.datetime) -> str:
    """Return the ISO8601-formatted representation of a datetime object.

    :param datetime datetime: The datetime.
    """
    pass

def pluck(dictlist: list[dict[str, typing.Any]], key: str):
    """Extracts a list of dictionary values from a list of dictionaries.
    ::

        >>> dlist = [{'id': 1, 'name': 'foo'}, {'id': 2, 'name': 'bar'}]
        >>> pluck(dlist, 'id')
        [1, 2]
    """
    pass

def get_value(obj, key: int | str, default=missing):
    """Helper for pulling a keyed value off various types of objects. Fields use
    this method by default to access attributes of the source object. For object `x`
    and attribute `i`, this method first tries to access `x[i]`, and then falls back to
    `x.i` if an exception is raised.

    .. warning::
        If an object `x` does not raise an exception when `x[i]` does not exist,
        `get_value` will never check the value `x.i`. Consider overriding
        `marshmallow.fields.Field.get_value` in this case.
    """
    pass

def set_value(dct: dict[str, typing.Any], key: str, value: typing.Any):
    """Set a value in a dict. If `key` contains a '.', it is assumed
    be a path (i.e. dot-delimited string) to the value's location.

    ::

        >>> d = {}
        >>> set_value(d, 'foo.bar', 42)
        >>> d
        {'foo': {'bar': 42}}
    """
    pass

def callable_or_raise(obj):
    """Check that an object is callable, else raise a :exc:`TypeError`."""
    pass

def get_func_args(func: typing.Callable) -> list[str]:
    """Given a callable, return a list of argument names. Handles
    `functools.partial` objects and class-based callables.

    .. versionchanged:: 3.0.0a1
        Do not return bound arguments, eg. ``self``.
    """
    pass

def resolve_field_instance(cls_or_instance):
    """Return a Schema instance from a Schema class or instance.

    :param type|Schema cls_or_instance: Marshmallow Schema class or instance.
    """
    pass

def timedelta_to_microseconds(value: dt.timedelta) -> int:
    """Compute the total microseconds of a timedelta

    https://github.com/python/cpython/blob/bb3e0c240bc60fe08d332ff5955d54197f79751c/Lib/datetime.py#L665-L667  # noqa: B950
    """
    pass--- validate ---
"""Validation classes for various types of data."""
from __future__ import annotations
import re
import typing
from abc import ABC, abstractmethod
from itertools import zip_longest
from operator import attrgetter
from marshmallow import types
from marshmallow.exceptions import ValidationError
_T = typing.TypeVar('_T')

class Validator(ABC):
    """Abstract base class for validators.

    .. note::
        This class does not provide any validation behavior. It is only used to
        add a useful `__repr__` implementation for validators.
    """
    error = None

    def __repr__(self) -> str:
        args = self._repr_args()
        args = f'{args}, ' if args else ''
        return f'<{self.__class__.__name__}({args}error={self.error!r})>'

    def _repr_args(self) -> str:
        """A string representation of the args passed to this validator. Used by
        `__repr__`.
        """
        pass

    @abstractmethod
    def __call__(self, value: typing.Any) -> typing.Any:
        ...

class And(Validator):
    """Compose multiple validators and combine their error messages.

    Example: ::

        from marshmallow import validate, ValidationError


        def is_even(value):
            if value % 2 != 0:
                raise ValidationError("Not an even value.")


        validator = validate.And(validate.Range(min=0), is_even)
        validator(-1)
        # ValidationError: ['Must be greater than or equal to 0.', 'Not an even value.']

    :param validators: Validators to combine.
    :param error: Error message to use when a validator returns ``False``.
    """
    default_error_message = 'Invalid value.'

    def __init__(self, *validators: types.Validator, error: str | None=None):
        self.validators = tuple(validators)
        self.error = error or self.default_error_message

    def __call__(self, value: typing.Any) -> typing.Any:
        errors = []
        kwargs = {}
        for validator in self.validators:
            try:
                r = validator(value)
                if not isinstance(validator, Validator) and r is False:
                    raise ValidationError(self.error)
            except ValidationError as err:
                kwargs.update(err.kwargs)
                if isinstance(err.messages, dict):
                    errors.append(err.messages)
                else:
                    errors.extend(typing.cast(list, err.messages))
        if errors:
            raise ValidationError(errors, **kwargs)
        return value

class URL(Validator):
    """Validate a URL.

    :param relative: Whether to allow relative URLs.
    :param absolute: Whether to allow absolute URLs.
    :param error: Error message to raise in case of a validation error.
        Can be interpolated with `{input}`.
    :param schemes: Valid schemes. By default, ``http``, ``https``,
        ``ftp``, and ``ftps`` are allowed.
    :param require_tld: Whether to reject non-FQDN hostnames.
    """

    class RegexMemoizer:

        def __init__(self):
            self._memoized = {}

        def __call__(self, relative: bool, absolute: bool, require_tld: bool) -> typing.Pattern:
            key = (relative, absolute, require_tld)
            if key not in self._memoized:
                self._memoized[key] = self._regex_generator(relative, absolute, require_tld)
            return self._memoized[key]
    _regex = RegexMemoizer()
    default_message = 'Not a valid URL.'
    default_schemes = {'http', 'https', 'ftp', 'ftps'}

    def __init__(self, *, relative: bool=False, absolute: bool=True, schemes: types.StrSequenceOrSet | None=None, require_tld: bool=True, error: str | None=None):
        if not relative and (not absolute):
            raise ValueError('URL validation cannot set both relative and absolute to False.')
        self.relative = relative
        self.absolute = absolute
        self.error = error or self.default_message
        self.schemes = schemes or self.default_schemes
        self.require_tld = require_tld

    def __call__(self, value: str) -> str:
        message = self._format_error(value)
        if not value:
            raise ValidationError(message)
        if '://' in value:
            scheme = value.split('://')[0].lower()
            if scheme not in self.schemes:
                raise ValidationError(message)
        regex = self._regex(self.relative, self.absolute, self.require_tld)
        if not regex.search(value):
            raise ValidationError(message)
        return value

class Email(Validator):
    """Validate an email address.

    :param error: Error message to raise in case of a validation error. Can be
        interpolated with `{input}`.
    """
    USER_REGEX = re.compile('(^[-!#$%&\'*+/=?^`{}|~\\w]+(\\.[-!#$%&\'*+/=?^`{}|~\\w]+)*\\Z|^"([\\001-\\010\\013\\014\\016-\\037!#-\\[\\]-\\177]|\\\\[\\001-\\011\\013\\014\\016-\\177])*"\\Z)', re.IGNORECASE | re.UNICODE)
    DOMAIN_REGEX = re.compile('(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}|[A-Z0-9-]{2,})\\Z|^\\[(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\]\\Z', re.IGNORECASE | re.UNICODE)
    DOMAIN_WHITELIST = ('localhost',)
    default_message = 'Not a valid email address.'

    def __init__(self, *, error: str | None=None):
        self.error = error or self.default_message

    def __call__(self, value: str) -> str:
        message = self._format_error(value)
        if not value or '@' not in value:
            raise ValidationError(message)
        user_part, domain_part = value.rsplit('@', 1)
        if not self.USER_REGEX.match(user_part):
            raise ValidationError(message)
        if domain_part not in self.DOMAIN_WHITELIST:
            if not self.DOMAIN_REGEX.match(domain_part):
                try:
                    domain_part = domain_part.encode('idna').decode('ascii')
                except UnicodeError:
                    pass
                else:
                    if self.DOMAIN_REGEX.match(domain_part):
                        return value
                raise ValidationError(message)
        return value

class Range(Validator):
    """Validator which succeeds if the value passed to it is within the specified
    range. If ``min`` is not specified, or is specified as `None`,
    no lower bound exists. If ``max`` is not specified, or is specified as `None`,
    no upper bound exists. The inclusivity of the bounds (if they exist) is configurable.
    If ``min_inclusive`` is not specified, or is specified as `True`, then
    the ``min`` bound is included in the range. If ``max_inclusive`` is not specified,
    or is specified as `True`, then the ``max`` bound is included in the range.

    :param min: The minimum value (lower bound). If not provided, minimum
        value will not be checked.
    :param max: The maximum value (upper bound). If not provided, maximum
        value will not be checked.
    :param min_inclusive: Whether the `min` bound is included in the range.
    :param max_inclusive: Whether the `max` bound is included in the range.
    :param error: Error message to raise in case of a validation error.
        Can be interpolated with `{input}`, `{min}` and `{max}`.
    """
    message_min = 'Must be {min_op} {{min}}.'
    message_max = 'Must be {max_op} {{max}}.'
    message_all = 'Must be {min_op} {{min}} and {max_op} {{max}}.'
    message_gte = 'greater than or equal to'
    message_gt = 'greater than'
    message_lte = 'less than or equal to'
    message_lt = 'less than'

    def __init__(self, min=None, max=None, *, min_inclusive: bool=True, max_inclusive: bool=True, error: str | None=None):
        self.min = min
        self.max = max
        self.error = error
        self.min_inclusive = min_inclusive
        self.max_inclusive = max_inclusive
        self.message_min = self.message_min.format(min_op=self.message_gte if self.min_inclusive else self.message_gt)
        self.message_max = self.message_max.format(max_op=self.message_lte if self.max_inclusive else self.message_lt)
        self.message_all = self.message_all.format(min_op=self.message_gte if self.min_inclusive else self.message_gt, max_op=self.message_lte if self.max_inclusive else self.message_lt)

    def __call__(self, value: _T) -> _T:
        if self.min is not None and (value < self.min if self.min_inclusive else value <= self.min):
            message = self.message_min if self.max is None else self.message_all
            raise ValidationError(self._format_error(value, message))
        if self.max is not None and (value > self.max if self.max_inclusive else value >= self.max):
            message = self.message_max if self.min is None else self.message_all
            raise ValidationError(self._format_error(value, message))
        return value

class Length(Validator):
    """Validator which succeeds if the value passed to it has a
    length between a minimum and maximum. Uses len(), so it
    can work for strings, lists, or anything with length.

    :param min: The minimum length. If not provided, minimum length
        will not be checked.
    :param max: The maximum length. If not provided, maximum length
        will not be checked.
    :param equal: The exact length. If provided, maximum and minimum
        length will not be checked.
    :param error: Error m<response clipped><NOTE>Due to the max output limit, only part of the full response has been shown to you.</NOTE>        """
        pass

    def fail(self, key: str, **kwargs):
        """Helper method that raises a `ValidationError` with an error message
        from ``self.error_messages``.

        .. deprecated:: 3.0.0
            Use `make_error <marshmallow.fields.Field.make_error>` instead.
        """
        pass

    def _validate_missing(self, value):
        """Validate missing values. Raise a :exc:`ValidationError` if
        `value` should be considered missing.
        """
        pass

    def serialize(self, attr: str, obj: typing.Any, accessor: typing.Callable[[typing.Any, str, typing.Any], typing.Any] | None=None, **kwargs):
        """Pulls the value for the given key from the object, applies the
        field's formatting and returns the result.

        :param attr: The attribute/key to get from the object.
        :param obj: The object to access the attribute/key from.
        :param accessor: Function used to access values from ``obj``.
        :param kwargs: Field-specific keyword arguments.
        """
        pass

    def deserialize(self, value: typing.Any, attr: str | None=None, data: typing.Mapping[str, typing.Any] | None=None, **kwargs):
        """Deserialize ``value``.

        :param value: The value to deserialize.
        :param attr: The attribute/key in `data` to deserialize.
        :param data: The raw input data passed to `Schema.load`.
        :param kwargs: Field-specific keyword arguments.
        :raise ValidationError: If an invalid value is passed or if a required value
            is missing.
        """
        pass

    def _bind_to_schema(self, field_name, schema):
        """Update field with values from its parent schema. Called by
        :meth:`Schema._bind_field <marshmallow.Schema._bind_field>`.

        :param str field_name: Field name set in schema.
        :param Schema|Field schema: Parent object.
        """
        pass

    def _serialize(self, value: typing.Any, attr: str | None, obj: typing.Any, **kwargs):
        """Serializes ``value`` to a basic Python datatype. Noop by default.
        Concrete :class:`Field` classes should implement this method.

        Example: ::

            class TitleCase(Field):
                def _serialize(self, value, attr, obj, **kwargs):
                    if not value:
                        return ""
                    return str(value).title()

        :param value: The value to be serialized.
        :param str attr: The attribute or key on the object to be serialized.
        :param object obj: The object the value was pulled from.
        :param dict kwargs: Field-specific keyword arguments.
        :return: The serialized value
        """
        pass

    def _deserialize(self, value: typing.Any, attr: str | None, data: typing.Mapping[str, typing.Any] | None, **kwargs):
        """Deserialize value. Concrete :class:`Field` classes should implement this method.

        :param value: The value to be deserialized.
        :param attr: The attribute/key in `data` to be deserialized.
        :param data: The raw input data passed to the `Schema.load`.
        :param kwargs: Field-specific keyword arguments.
        :raise ValidationError: In case of formatting or validation failure.
        :return: The deserialized value.

        .. versionchanged:: 2.0.0
            Added ``attr`` and ``data`` parameters.

        .. versionchanged:: 3.0.0
            Added ``**kwargs`` to signature.
        """
        pass

    @property
    def context(self):
        """The context dictionary for the parent :class:`Schema`."""
        pass

class Raw(Field):
    """Field that applies no formatting."""

class Nested(Field):
    """Allows you to nest a :class:`Schema <marshmallow.Schema>`
    inside a field.

    Examples: ::

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


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

    When passing a `Schema <marshmallow.Schema>` instance as the first argument,
    the instance's ``exclude``, ``only``, and ``many`` attributes will be respected.

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

    ::

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

        # No
        author = fields.Nested(UserSchema(), only=("id", "name"))

    :param nested: `Schema` instance, class, class name (string), dictionary, or callable that
        returns a `Schema` or dictionary. Dictionaries are converted with `Schema.from_dict`.
    :param exclude: A list or tuple of fields to exclude.
    :param only: A list or tuple of fields to marshal. If `None`, all fields are marshalled.
        This parameter takes precedence over ``exclude``.
    :param many: Whether the field is a collection of objects.
    :param unknown: Whether to exclude, include, or raise an error for unknown
        fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.
    :param kwargs: The same keyword arguments that :class:`Field` receives.
    """
    default_error_messages = {'type': 'Invalid type.'}

    def __init__(self, nested: SchemaABC | type | str | dict[str, Field | type] | typing.Callable[[], SchemaABC | type | dict[str, Field | type]], *, dump_default: typing.Any=missing_, default: typing.Any=missing_, only: types.StrSequenceOrSet | None=None, exclude: types.StrSequenceOrSet=(), many: bool=False, unknown: str | None=None, **kwargs):
        if only is not None and (not is_collection(only)):
            raise StringNotCollectionError('"only" should be a collection of strings.')
        if not is_collection(exclude):
            raise StringNotCollectionError('"exclude" should be a collection of strings.')
        if nested == 'self':
            warnings.warn("Passing 'self' to `Nested` is deprecated. Use `Nested(lambda: MySchema(...))` instead.", RemovedInMarshmallow4Warning, stacklevel=2)
        self.nested = nested
        self.only = only
        self.exclude = exclude
        self.many = many
        self.unknown = unknown
        self._schema = None
        super().__init__(default=default, dump_default=dump_default, **kwargs)

    @property
    def schema(self):
        """The nested Schema object.

        .. versionchanged:: 1.0.0
            Renamed from `serializer` to `schema`.
        """
        pass

    def _deserialize(self, value, attr, data, partial=None, **kwargs):
        """Same as :meth:`Field._deserialize` with additional ``partial`` argument.

        :param bool|tuple partial: For nested schemas, the ``partial``
            parameter passed to `Schema.load`.

        .. versionchanged:: 3.0.0
            Add ``partial`` parameter.
        """
        pass

class Pluck(Nested):
    """Allows you to replace nested data with one of the data's fields.

    Example: ::

        from marshmallow import Schema, fields


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


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


        in_data = {"artist": 42}
        loaded = AlbumSchema().load(in_data)  # => {'artist': {'id': 42}}
        dumped = AlbumSchema().dump(loaded)  # => {'artist': 42}

    :param Schema nested: The Schema class or class name (string)
        to nest, or ``"self"`` to nest the :class:`Schema` within itself.
    :param str field_name: The key to pluck a value from.
    :param kwargs: The same keyword arguments that :class:`Nested` receives.
    """

    def __init__(self, nested: SchemaABC | type | str | typing.Callable[[], SchemaABC], field_name: str, **kwargs):
        super().__init__(nested, only=(field_name,), **kwargs)
        self.field_name = field_name

class List(Field):
    """A list field, composed with another `Field` class or
    instance.

    Example: ::

        numbers = fields.List(fields.Float())

    :param cls_or_instance: A field class or instance.
    :param kwargs: The same keyword arguments that :class:`Field` receives.

    .. versionchanged:: 2.0.0
        The ``allow_none`` parameter now applies to deserialization and
        has the same semantics as the other fields.

    .. versionchanged:: 3.0.0rc9
        Does not serialize scalar values to single-item lists.
    """
    default_error_messages = {'invalid': 'Not a valid list.'}

    def __init__(self, cls_or_instance: Field | type, **kwargs):
        super().__init__(**kwargs)
        try:
            self.inner = resolve_field_instance(cls_or_instance)
        except FieldInstanceResolutionError as error:
            raise ValueError('The list elements must be a subclass or instance of marshmallow.base.FieldABC.') from error
        if isinstance(self.inner, Nested):
            self.only = self.inner.only
            self.exclude = self.inner.exclude

class Tuple(Field):
    """A tuple field, composed of a fixed number of other `Field` classes or
    instances

    Example: ::

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

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

    :param Iterable[Field] tuple_fields: An iterable of field classes or
        instances.
    :param kwargs: The same keyword arguments that :class:`Field` receives.

    .. versionadded:: 3.0.0rc4
    """
    default_error_messages = {'invalid': 'Not a valid tuple.'}

    def __init__(self, tuple_fields, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not utils.is_collection(tuple_fields):
            raise ValueError('tuple_fields must be an iterable of Field classes or instances.')
        try:
            self.tuple_fields = [resolve_field_instance(cls_or_instance) for cls_or_instance in tuple_fields]
        except FieldInstanceResolutionError as error:
            raise ValueError('Elements of "tuple_fields" must be subclasses or instances of marshmallow.base.FieldABC.') from error
        self.validate_length = Length(equal=len(self.tuple_fields))

class String(Field):
    """A string field.

    :param kwargs: The same keyword arguments that :class:`Field` receives.
    """
    default_error_messages = {'invalid': 'Not a valid string.', 'invalid_utf8': 'Not a valid utf-8 string.'}

class UUID(String):
    """A UUID field."""
    default_error_messages = {'invalid_uuid': 'Not a valid UUID.'}

    def _validated(self, value) -> uuid.UUID | None:
        """Format the value or raise a :exc:`ValidationError` if an error occurs."""
        pass

class Number(Field):
    """Base class for number fields.

    :param bool as_string: If `True`, format the serialized value as a string.
    :param kwargs: The same keyword arguments that :class:`Field` receives.
    """
    num_type = float
    default_error_messages = {'invalid': 'Not a valid number.', 'too_large': 'Number too large.'}

    def __init__(self, *, as_string: bool=False, **kwargs):
        self.as_string = as_string
        super().__init__(**kwargs)

    def _format_num(self, value) -> typing.Any:
        """Return the number value for value, given this field's `num_type`."""
        pass

    def _validated(self, value) -> _T | None:
        """Format the value or raise a :exc:`ValidationError` if an error occurs."""
        pass

    def _serialize(self, value, attr, obj, **kwargs) -> str | _T | None:
        """Return a string if `self.as_string=True`, otherwise return this field's `num_type`."""
        pass

class Integer(Number):
    """An integer field.

    :param strict: If `True`, only integer types are valid.
        Otherwise, any value castable to `int` is valid.
    :param kwargs: The same keyword arguments that :class:`Number` receives.
    """
    num_type = int
    default_error_messages = {'invalid': 'Not a valid integer.'}

    def __init__(self, *, strict: bool=False, **kwargs):
        self.strict = strict
        super().__init__(**kwargs)

class Float(Number):
    """A double as an IEEE-754 double precision string.

    :param bool allow_nan: If `True`, `NaN`, `Infinity` and `-Infinity` are allowed,
        even though they are illegal according to the JSON specification.
    :param bool as_string: If `True`, format the value as a string.
    :param kwargs: The same keyword arguments that :class:`Number` receives.
    """
    num_type = float
    default_error_messages = {'special': 'Special numeric values (nan or infinity) are not permitted.'}

    def __init__(self, *, allow_nan: bool=False, as_string: bool=False, **kwargs):
        self.allow_nan = allow_nan
        super().__init__(as_string=as_string, **kwargs)

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

    .. warning::

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

    .. warning::

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

    :param places: How many decimal places to quantize the value. If `None`, does
        not quantize the value.
    :param rounding: How to round the value during quantize, for example
        `decimal.ROUND_UP`. If `None`, uses the rounding value from
        the current thread's context.
    :param allow_nan: If `True`, `NaN`, `Infinity` and `-Infinity` are allowed,
        even though they are illegal according to the JSON specification.
[The command completed with exit code 0.]
[Current working directory: /workspace/marshmallow]
[Python interpreter: /usr/bin/python]
[Command finished with exit code 0]