Browse Source

Update attr 19.2.0.dev0 (daf2bc8) → 20.1.0.dev0 (9b5e988).

pull/1289/head
JackDandy 5 years ago
parent
commit
4751f24caa
  1. 1
      CHANGES.md
  2. 5
      lib/attr/__init__.py
  3. 59
      lib/attr/__init__.pyi
  4. 6
      lib/attr/_funcs.py
  5. 388
      lib/attr/_make.py
  6. 85
      lib/attr/_version_info.py
  7. 9
      lib/attr/_version_info.pyi
  8. 4
      lib/attr/converters.py
  9. 2
      lib/attr/converters.pyi
  10. 2
      lib/attr/exceptions.py
  11. 10
      lib/attr/filters.py
  12. 99
      lib/attr/validators.py
  13. 35
      lib/attr/validators.pyi

1
CHANGES.md

@ -5,6 +5,7 @@
* Change improve performance for find_show_by_id * Change improve performance for find_show_by_id
* Change episode overview, move pulldown from 'Set/Failed' to 'Override/Failed' * Change episode overview, move pulldown from 'Set/Failed' to 'Override/Failed'
* Update Apprise 0.8.0 (6aa52c3) to 0.8.3 (4aee9de) * Update Apprise 0.8.0 (6aa52c3) to 0.8.3 (4aee9de)
* Update attr 19.2.0.dev0 (daf2bc8) to 20.1.0.dev0 (9b5e988)
[develop changelog] [develop changelog]

5
lib/attr/__init__.py

@ -16,9 +16,11 @@ from ._make import (
make_class, make_class,
validate, validate,
) )
from ._version_info import VersionInfo
__version__ = "19.2.0.dev0" __version__ = "20.1.0.dev0"
__version_info__ = VersionInfo._from_version_string(__version__)
__title__ = "attrs" __title__ = "attrs"
__description__ = "Classes Without Boilerplate" __description__ = "Classes Without Boilerplate"
@ -37,6 +39,7 @@ s = attributes = attrs
ib = attr = attrib ib = attr = attrib
dataclass = partial(attrs, auto_attribs=True) # happy Easter ;) dataclass = partial(attrs, auto_attribs=True) # happy Easter ;)
__all__ = [ __all__ = [
"Attribute", "Attribute",
"Factory", "Factory",

59
lib/attr/__init__.pyi

@ -20,12 +20,27 @@ from . import filters as filters
from . import converters as converters from . import converters as converters
from . import validators as validators from . import validators as validators
from ._version_info import VersionInfo
__version__: str
__version_info__: VersionInfo
__title__: str
__description__: str
__url__: str
__uri__: str
__author__: str
__email__: str
__license__: str
__copyright__: str
_T = TypeVar("_T") _T = TypeVar("_T")
_C = TypeVar("_C", bound=type) _C = TypeVar("_C", bound=type)
_ValidatorType = Callable[[Any, Attribute[_T], _T], Any] _ValidatorType = Callable[[Any, Attribute[_T], _T], Any]
_ConverterType = Callable[[Any], _T] _ConverterType = Callable[[Any], _T]
_FilterType = Callable[[Attribute[_T], _T], bool] _FilterType = Callable[[Attribute[_T], _T], bool]
_ReprType = Callable[[Any], str]
_ReprArgType = Union[bool, _ReprType]
# FIXME: in reality, if multiple validators are passed they must be in a list or tuple, # FIXME: in reality, if multiple validators are passed they must be in a list or tuple,
# but those are invariant and so would prevent subtypes of _ValidatorType from working # but those are invariant and so would prevent subtypes of _ValidatorType from working
# when passed in a list or tuple. # when passed in a list or tuple.
@ -49,18 +64,16 @@ class Attribute(Generic[_T]):
name: str name: str
default: Optional[_T] default: Optional[_T]
validator: Optional[_ValidatorType[_T]] validator: Optional[_ValidatorType[_T]]
repr: bool repr: _ReprArgType
cmp: bool cmp: bool
eq: bool
order: bool
hash: Optional[bool] hash: Optional[bool]
init: bool init: bool
converter: Optional[_ConverterType[_T]] converter: Optional[_ConverterType[_T]]
metadata: Dict[Any, Any] metadata: Dict[Any, Any]
type: Optional[Type[_T]] type: Optional[Type[_T]]
kw_only: bool kw_only: bool
def __lt__(self, x: Attribute[_T]) -> bool: ...
def __le__(self, x: Attribute[_T]) -> bool: ...
def __gt__(self, x: Attribute[_T]) -> bool: ...
def __ge__(self, x: Attribute[_T]) -> bool: ...
# NOTE: We had several choices for the annotation to use for type arg: # NOTE: We had several choices for the annotation to use for type arg:
# 1) Type[_T] # 1) Type[_T]
@ -89,8 +102,8 @@ class Attribute(Generic[_T]):
def attrib( def attrib(
default: None = ..., default: None = ...,
validator: None = ..., validator: None = ...,
repr: bool = ..., repr: _ReprArgType = ...,
cmp: bool = ..., cmp: Optional[bool] = ...,
hash: Optional[bool] = ..., hash: Optional[bool] = ...,
init: bool = ..., init: bool = ...,
metadata: Optional[Mapping[Any, Any]] = ..., metadata: Optional[Mapping[Any, Any]] = ...,
@ -98,6 +111,8 @@ def attrib(
converter: None = ..., converter: None = ...,
factory: None = ..., factory: None = ...,
kw_only: bool = ..., kw_only: bool = ...,
eq: Optional[bool] = ...,
order: Optional[bool] = ...,
) -> Any: ... ) -> Any: ...
# This form catches an explicit None or no default and infers the type from the other arguments. # This form catches an explicit None or no default and infers the type from the other arguments.
@ -105,8 +120,8 @@ def attrib(
def attrib( def attrib(
default: None = ..., default: None = ...,
validator: Optional[_ValidatorArgType[_T]] = ..., validator: Optional[_ValidatorArgType[_T]] = ...,
repr: bool = ..., repr: _ReprArgType = ...,
cmp: bool = ..., cmp: Optional[bool] = ...,
hash: Optional[bool] = ..., hash: Optional[bool] = ...,
init: bool = ..., init: bool = ...,
metadata: Optional[Mapping[Any, Any]] = ..., metadata: Optional[Mapping[Any, Any]] = ...,
@ -114,6 +129,8 @@ def attrib(
converter: Optional[_ConverterType[_T]] = ..., converter: Optional[_ConverterType[_T]] = ...,
factory: Optional[Callable[[], _T]] = ..., factory: Optional[Callable[[], _T]] = ...,
kw_only: bool = ..., kw_only: bool = ...,
eq: Optional[bool] = ...,
order: Optional[bool] = ...,
) -> _T: ... ) -> _T: ...
# This form catches an explicit default argument. # This form catches an explicit default argument.
@ -121,8 +138,8 @@ def attrib(
def attrib( def attrib(
default: _T, default: _T,
validator: Optional[_ValidatorArgType[_T]] = ..., validator: Optional[_ValidatorArgType[_T]] = ...,
repr: bool = ..., repr: _ReprArgType = ...,
cmp: bool = ..., cmp: Optional[bool] = ...,
hash: Optional[bool] = ..., hash: Optional[bool] = ...,
init: bool = ..., init: bool = ...,
metadata: Optional[Mapping[Any, Any]] = ..., metadata: Optional[Mapping[Any, Any]] = ...,
@ -130,6 +147,8 @@ def attrib(
converter: Optional[_ConverterType[_T]] = ..., converter: Optional[_ConverterType[_T]] = ...,
factory: Optional[Callable[[], _T]] = ..., factory: Optional[Callable[[], _T]] = ...,
kw_only: bool = ..., kw_only: bool = ...,
eq: Optional[bool] = ...,
order: Optional[bool] = ...,
) -> _T: ... ) -> _T: ...
# This form covers type=non-Type: e.g. forward references (str), Any # This form covers type=non-Type: e.g. forward references (str), Any
@ -137,8 +156,8 @@ def attrib(
def attrib( def attrib(
default: Optional[_T] = ..., default: Optional[_T] = ...,
validator: Optional[_ValidatorArgType[_T]] = ..., validator: Optional[_ValidatorArgType[_T]] = ...,
repr: bool = ..., repr: _ReprArgType = ...,
cmp: bool = ..., cmp: Optional[bool] = ...,
hash: Optional[bool] = ..., hash: Optional[bool] = ...,
init: bool = ..., init: bool = ...,
metadata: Optional[Mapping[Any, Any]] = ..., metadata: Optional[Mapping[Any, Any]] = ...,
@ -146,6 +165,8 @@ def attrib(
converter: Optional[_ConverterType[_T]] = ..., converter: Optional[_ConverterType[_T]] = ...,
factory: Optional[Callable[[], _T]] = ..., factory: Optional[Callable[[], _T]] = ...,
kw_only: bool = ..., kw_only: bool = ...,
eq: Optional[bool] = ...,
order: Optional[bool] = ...,
) -> Any: ... ) -> Any: ...
@overload @overload
def attrs( def attrs(
@ -153,7 +174,7 @@ def attrs(
these: Optional[Dict[str, Any]] = ..., these: Optional[Dict[str, Any]] = ...,
repr_ns: Optional[str] = ..., repr_ns: Optional[str] = ...,
repr: bool = ..., repr: bool = ...,
cmp: bool = ..., cmp: Optional[bool] = ...,
hash: Optional[bool] = ..., hash: Optional[bool] = ...,
init: bool = ..., init: bool = ...,
slots: bool = ..., slots: bool = ...,
@ -164,6 +185,8 @@ def attrs(
kw_only: bool = ..., kw_only: bool = ...,
cache_hash: bool = ..., cache_hash: bool = ...,
auto_exc: bool = ..., auto_exc: bool = ...,
eq: Optional[bool] = ...,
order: Optional[bool] = ...,
) -> _C: ... ) -> _C: ...
@overload @overload
def attrs( def attrs(
@ -171,7 +194,7 @@ def attrs(
these: Optional[Dict[str, Any]] = ..., these: Optional[Dict[str, Any]] = ...,
repr_ns: Optional[str] = ..., repr_ns: Optional[str] = ...,
repr: bool = ..., repr: bool = ...,
cmp: bool = ..., cmp: Optional[bool] = ...,
hash: Optional[bool] = ..., hash: Optional[bool] = ...,
init: bool = ..., init: bool = ...,
slots: bool = ..., slots: bool = ...,
@ -182,6 +205,8 @@ def attrs(
kw_only: bool = ..., kw_only: bool = ...,
cache_hash: bool = ..., cache_hash: bool = ...,
auto_exc: bool = ..., auto_exc: bool = ...,
eq: Optional[bool] = ...,
order: Optional[bool] = ...,
) -> Callable[[_C], _C]: ... ) -> Callable[[_C], _C]: ...
# TODO: add support for returning NamedTuple from the mypy plugin # TODO: add support for returning NamedTuple from the mypy plugin
@ -200,7 +225,7 @@ def make_class(
bases: Tuple[type, ...] = ..., bases: Tuple[type, ...] = ...,
repr_ns: Optional[str] = ..., repr_ns: Optional[str] = ...,
repr: bool = ..., repr: bool = ...,
cmp: bool = ..., cmp: Optional[bool] = ...,
hash: Optional[bool] = ..., hash: Optional[bool] = ...,
init: bool = ..., init: bool = ...,
slots: bool = ..., slots: bool = ...,
@ -211,6 +236,8 @@ def make_class(
kw_only: bool = ..., kw_only: bool = ...,
cache_hash: bool = ..., cache_hash: bool = ...,
auto_exc: bool = ..., auto_exc: bool = ...,
eq: Optional[bool] = ...,
order: Optional[bool] = ...,
) -> type: ... ) -> type: ...
# _funcs -- # _funcs --

6
lib/attr/_funcs.py

@ -24,7 +24,7 @@ def asdict(
``attrs``-decorated. ``attrs``-decorated.
:param callable filter: A callable whose return code determines whether an :param callable filter: A callable whose return code determines whether an
attribute or element is included (``True``) or dropped (``False``). Is attribute or element is included (``True``) or dropped (``False``). Is
called with the :class:`attr.Attribute` as the first argument and the called with the `attr.Attribute` as the first argument and the
value as the second argument. value as the second argument.
:param callable dict_factory: A callable to produce dictionaries from. For :param callable dict_factory: A callable to produce dictionaries from. For
example, to produce ordered dictionaries instead of normal Python example, to produce ordered dictionaries instead of normal Python
@ -130,7 +130,7 @@ def astuple(
``attrs``-decorated. ``attrs``-decorated.
:param callable filter: A callable whose return code determines whether an :param callable filter: A callable whose return code determines whether an
attribute or element is included (``True``) or dropped (``False``). Is attribute or element is included (``True``) or dropped (``False``). Is
called with the :class:`attr.Attribute` as the first argument and the called with the `attr.Attribute` as the first argument and the
value as the second argument. value as the second argument.
:param callable tuple_factory: A callable to produce tuples from. For :param callable tuple_factory: A callable to produce tuples from. For
example, to produce lists instead of tuples. example, to produce lists instead of tuples.
@ -239,7 +239,7 @@ def assoc(inst, **changes):
class. class.
.. deprecated:: 17.1.0 .. deprecated:: 17.1.0
Use :func:`evolve` instead. Use `evolve` instead.
""" """
import warnings import warnings

388
lib/attr/_make.py

@ -74,7 +74,7 @@ def attrib(
default=NOTHING, default=NOTHING,
validator=None, validator=None,
repr=True, repr=True,
cmp=True, cmp=None,
hash=None, hash=None,
init=True, init=True,
metadata=None, metadata=None,
@ -82,6 +82,8 @@ def attrib(
converter=None, converter=None,
factory=None, factory=None,
kw_only=False, kw_only=False,
eq=None,
order=None,
): ):
""" """
Create a new attribute on a class. Create a new attribute on a class.
@ -89,30 +91,30 @@ def attrib(
.. warning:: .. warning::
Does *not* do anything unless the class is also decorated with Does *not* do anything unless the class is also decorated with
:func:`attr.s`! `attr.s`!
:param default: A value that is used if an ``attrs``-generated ``__init__`` :param default: A value that is used if an ``attrs``-generated ``__init__``
is used and no value is passed while instantiating or the attribute is is used and no value is passed while instantiating or the attribute is
excluded using ``init=False``. excluded using ``init=False``.
If the value is an instance of :class:`Factory`, its callable will be If the value is an instance of `Factory`, its callable will be
used to construct a new value (useful for mutable data types like lists used to construct a new value (useful for mutable data types like lists
or dicts). or dicts).
If a default is not set (or set manually to ``attr.NOTHING``), a value If a default is not set (or set manually to ``attr.NOTHING``), a value
*must* be supplied when instantiating; otherwise a :exc:`TypeError` *must* be supplied when instantiating; otherwise a `TypeError`
will be raised. will be raised.
The default can also be set using decorator notation as shown below. The default can also be set using decorator notation as shown below.
:type default: Any value. :type default: Any value
:param callable factory: Syntactic sugar for :param callable factory: Syntactic sugar for
``default=attr.Factory(callable)``. ``default=attr.Factory(callable)``.
:param validator: :func:`callable` that is called by ``attrs``-generated :param validator: `callable` that is called by ``attrs``-generated
``__init__`` methods after the instance has been initialized. They ``__init__`` methods after the instance has been initialized. They
receive the initialized instance, the :class:`Attribute`, and the receive the initialized instance, the `Attribute`, and the
passed value. passed value.
The return value is *not* inspected so the validator has to throw an The return value is *not* inspected so the validator has to throw an
@ -122,18 +124,29 @@ def attrib(
all pass. all pass.
Validators can be globally disabled and re-enabled using Validators can be globally disabled and re-enabled using
:func:`get_run_validators`. `get_run_validators`.
The validator can also be set using decorator notation as shown below. The validator can also be set using decorator notation as shown below.
:type validator: ``callable`` or a ``list`` of ``callable``\\ s. :type validator: ``callable`` or a ``list`` of ``callable``\\ s.
:param bool repr: Include this attribute in the generated ``__repr__`` :param repr: Include this attribute in the generated ``__repr__``
method. method. If ``True``, include the attribute; if ``False``, omit it. By
:param bool cmp: Include this attribute in the generated comparison methods default, the built-in ``repr()`` function is used. To override how the
(``__eq__`` et al). attribute value is formatted, pass a ``callable`` that takes a single
value and returns a string. Note that the resulting string is used
as-is, i.e. it will be used directly *instead* of calling ``repr()``
(the default).
:type repr: a ``bool`` or a ``callable`` to use a custom function.
:param bool eq: If ``True`` (default), include this attribute in the
generated ``__eq__`` and ``__ne__`` methods that check two instances
for equality.
:param bool order: If ``True`` (default), include this attributes in the
generated ``__lt__``, ``__le__``, ``__gt__`` and ``__ge__`` methods.
:param bool cmp: Setting to ``True`` is equivalent to setting ``eq=True,
order=True``. Deprecated in favor of *eq* and *order*.
:param hash: Include this attribute in the generated ``__hash__`` :param hash: Include this attribute in the generated ``__hash__``
method. If ``None`` (default), mirror *cmp*'s value. This is the method. If ``None`` (default), mirror *eq*'s value. This is the
correct behavior according the Python spec. Setting this value to correct behavior according the Python spec. Setting this value to
anything else than ``None`` is *discouraged*. anything else than ``None`` is *discouraged*.
:type hash: ``bool`` or ``None`` :type hash: ``bool`` or ``None``
@ -141,13 +154,13 @@ def attrib(
method. It is possible to set this to ``False`` and set a default method. It is possible to set this to ``False`` and set a default
value. In that case this attributed is unconditionally initialized value. In that case this attributed is unconditionally initialized
with the specified default value or factory. with the specified default value or factory.
:param callable converter: :func:`callable` that is called by :param callable converter: `callable` that is called by
``attrs``-generated ``__init__`` methods to converter attribute's value ``attrs``-generated ``__init__`` methods to convert attribute's value
to the desired format. It is given the passed-in value, and the to the desired format. It is given the passed-in value, and the
returned value will be used as the new value of the attribute. The returned value will be used as the new value of the attribute. The
value is converted before being passed to the validator, if any. value is converted before being passed to the validator, if any.
:param metadata: An arbitrary mapping, to be used by third-party :param metadata: An arbitrary mapping, to be used by third-party
components. See :ref:`extending_metadata`. components. See `extending_metadata`.
:param type: The type of the attribute. In Python 3.6 or greater, the :param type: The type of the attribute. In Python 3.6 or greater, the
preferred method to specify the type is using a variable annotation preferred method to specify the type is using a variable annotation
(see `PEP 526 <https://www.python.org/dev/peps/pep-0526/>`_). (see `PEP 526 <https://www.python.org/dev/peps/pep-0526/>`_).
@ -157,7 +170,7 @@ def attrib(
Please note that ``attrs`` doesn't do anything with this metadata by Please note that ``attrs`` doesn't do anything with this metadata by
itself. You can use it as part of your own code or for itself. You can use it as part of your own code or for
:doc:`static type checking <types>`. `static type checking <types>`.
:param kw_only: Make this attribute keyword-only (Python 3+) :param kw_only: Make this attribute keyword-only (Python 3+)
in the generated ``__init__`` (if ``init`` is ``False``, this in the generated ``__init__`` (if ``init`` is ``False``, this
parameter is ignored). parameter is ignored).
@ -166,7 +179,7 @@ def attrib(
.. versionadded:: 16.3.0 *metadata* .. versionadded:: 16.3.0 *metadata*
.. versionchanged:: 17.1.0 *validator* can be a ``list`` now. .. versionchanged:: 17.1.0 *validator* can be a ``list`` now.
.. versionchanged:: 17.1.0 .. versionchanged:: 17.1.0
*hash* is ``None`` and therefore mirrors *cmp* by default. *hash* is ``None`` and therefore mirrors *eq* by default.
.. versionadded:: 17.3.0 *type* .. versionadded:: 17.3.0 *type*
.. deprecated:: 17.4.0 *convert* .. deprecated:: 17.4.0 *convert*
.. versionadded:: 17.4.0 *converter* as a replacement for the deprecated .. versionadded:: 17.4.0 *converter* as a replacement for the deprecated
@ -175,7 +188,12 @@ def attrib(
``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``. ``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``.
.. versionadded:: 18.2.0 *kw_only* .. versionadded:: 18.2.0 *kw_only*
.. versionchanged:: 19.2.0 *convert* keyword argument removed .. versionchanged:: 19.2.0 *convert* keyword argument removed
.. versionchanged:: 19.2.0 *repr* also accepts a custom callable.
.. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01.
.. versionadded:: 19.2.0 *eq* and *order*
""" """
eq, order = _determine_eq_order(cmp, eq, order)
if hash is not None and hash is not True and hash is not False: if hash is not None and hash is not True and hash is not False:
raise TypeError( raise TypeError(
"Invalid value for hash. Must be True, False, or None." "Invalid value for hash. Must be True, False, or None."
@ -198,13 +216,15 @@ def attrib(
default=default, default=default,
validator=validator, validator=validator,
repr=repr, repr=repr,
cmp=cmp, cmp=None,
hash=hash, hash=hash,
init=init, init=init,
converter=converter, converter=converter,
metadata=metadata, metadata=metadata,
type=type, type=type,
kw_only=kw_only, kw_only=kw_only,
eq=eq,
order=order,
) )
@ -489,7 +509,7 @@ class _ClassBuilder(object):
for name in self._attr_names: for name in self._attr_names:
if ( if (
name not in base_names name not in base_names
and getattr(cls, name, _sentinel) != _sentinel and getattr(cls, name, _sentinel) is not _sentinel
): ):
try: try:
delattr(cls, name) delattr(cls, name)
@ -517,11 +537,19 @@ class _ClassBuilder(object):
"See https://github.com/python-attrs/attrs/issues/494 ." "See https://github.com/python-attrs/attrs/issues/494 ."
) )
# Clears the cached hash state on serialization; for frozen
# classes we need to bypass the class's setattr method.
if self._frozen:
def cache_hash_set_state(chss_self, _):
object.__setattr__(chss_self, _hash_cache_field, None)
else:
def cache_hash_set_state(chss_self, _): def cache_hash_set_state(chss_self, _):
# clear hash code cache
setattr(chss_self, _hash_cache_field, None) setattr(chss_self, _hash_cache_field, None)
setattr(cls, "__setstate__", cache_hash_set_state) cls.__setstate__ = cache_hash_set_state
return cls return cls
@ -672,14 +700,22 @@ class _ClassBuilder(object):
return self return self
def add_cmp(self): def add_eq(self):
cd = self._cls_dict
cd["__eq__"], cd["__ne__"] = (
self._add_method_dunders(meth)
for meth in _make_eq(self._cls, self._attrs)
)
return self
def add_order(self):
cd = self._cls_dict cd = self._cls_dict
cd["__eq__"], cd["__ne__"], cd["__lt__"], cd["__le__"], cd[ cd["__lt__"], cd["__le__"], cd["__gt__"], cd["__ge__"] = (
"__gt__"
], cd["__ge__"] = (
self._add_method_dunders(meth) self._add_method_dunders(meth)
for meth in _make_cmp(self._cls, self._attrs) for meth in _make_order(self._cls, self._attrs)
) )
return self return self
@ -703,12 +739,45 @@ class _ClassBuilder(object):
return method return method
_CMP_DEPRECATION = (
"The usage of `cmp` is deprecated and will be removed on or after "
"2021-06-01. Please use `eq` and `order` instead."
)
def _determine_eq_order(cmp, eq, order):
"""
Validate the combination of *cmp*, *eq*, and *order*. Derive the effective
values of eq and order.
"""
if cmp is not None and any((eq is not None, order is not None)):
raise ValueError("Don't mix `cmp` with `eq' and `order`.")
# cmp takes precedence due to bw-compatibility.
if cmp is not None:
warnings.warn(_CMP_DEPRECATION, DeprecationWarning, stacklevel=3)
return cmp, cmp
# If left None, equality is on and ordering mirrors equality.
if eq is None:
eq = True
if order is None:
order = eq
if eq is False and order is True:
raise ValueError("`order` can only be True if `eq` is True too.")
return eq, order
def attrs( def attrs(
maybe_cls=None, maybe_cls=None,
these=None, these=None,
repr_ns=None, repr_ns=None,
repr=True, repr=True,
cmp=True, cmp=None,
hash=None, hash=None,
init=True, init=True,
slots=False, slots=False,
@ -719,13 +788,15 @@ def attrs(
kw_only=False, kw_only=False,
cache_hash=False, cache_hash=False,
auto_exc=False, auto_exc=False,
eq=None,
order=None,
): ):
r""" r"""
A class decorator that adds `dunder A class decorator that adds `dunder
<https://wiki.python.org/moin/DunderAlias>`_\ -methods according to the <https://wiki.python.org/moin/DunderAlias>`_\ -methods according to the
specified attributes using :func:`attr.ib` or the *these* argument. specified attributes using `attr.ib` or the *these* argument.
:param these: A dictionary of name to :func:`attr.ib` mappings. This is :param these: A dictionary of name to `attr.ib` mappings. This is
useful to avoid the definition of your attributes within the class body useful to avoid the definition of your attributes within the class body
because you can't (e.g. if you want to add ``__repr__`` methods to because you can't (e.g. if you want to add ``__repr__`` methods to
Django models) or don't want to. Django models) or don't want to.
@ -733,12 +804,12 @@ def attrs(
If *these* is not ``None``, ``attrs`` will *not* search the class body If *these* is not ``None``, ``attrs`` will *not* search the class body
for attributes and will *not* remove any attributes from it. for attributes and will *not* remove any attributes from it.
If *these* is an ordered dict (:class:`dict` on Python 3.6+, If *these* is an ordered dict (`dict` on Python 3.6+,
:class:`collections.OrderedDict` otherwise), the order is deduced from `collections.OrderedDict` otherwise), the order is deduced from
the order of the attributes inside *these*. Otherwise the order the order of the attributes inside *these*. Otherwise the order
of the definition of the attributes is used. of the definition of the attributes is used.
:type these: :class:`dict` of :class:`str` to :func:`attr.ib` :type these: `dict` of `str` to `attr.ib`
:param str repr_ns: When using nested classes, there's no way in Python 2 :param str repr_ns: When using nested classes, there's no way in Python 2
to automatically detect that. Therefore it's possible to set the to automatically detect that. Therefore it's possible to set the
@ -747,18 +818,29 @@ def attrs(
representation of ``attrs`` attributes.. representation of ``attrs`` attributes..
:param bool str: Create a ``__str__`` method that is identical to :param bool str: Create a ``__str__`` method that is identical to
``__repr__``. This is usually not necessary except for ``__repr__``. This is usually not necessary except for
:class:`Exception`\ s. `Exception`\ s.
:param bool cmp: Create ``__eq__``, ``__ne__``, ``__lt__``, ``__le__``, :param bool eq: If ``True`` or ``None`` (default), add ``__eq__`` and
``__gt__``, and ``__ge__`` methods that compare the class as if it were ``__ne__`` methods that check two instances for equality.
a tuple of its ``attrs`` attributes. But the attributes are *only*
compared, if the types of both classes are *identical*! They compare the instances as if they were tuples of their ``attrs``
attributes if and only if the types of both classes are *identical*!
:type eq: `bool` or `None`
:param bool order: If ``True``, add ``__lt__``, ``__le__``, ``__gt__``,
and ``__ge__`` methods that behave like *eq* above and allow instances
to be ordered. If ``None`` (default) mirror value of *eq*.
:type order: `bool` or `None`
:param cmp: Setting to ``True`` is equivalent to setting ``eq=True,
order=True``. Deprecated in favor of *eq* and *order*, has precedence
over them for backward-compatibility though. Must not be mixed with
*eq* or *order*.
:type cmp: `bool` or `None`
:param hash: If ``None`` (default), the ``__hash__`` method is generated :param hash: If ``None`` (default), the ``__hash__`` method is generated
according how *cmp* and *frozen* are set. according how *eq* and *frozen* are set.
1. If *both* are True, ``attrs`` will generate a ``__hash__`` for you. 1. If *both* are True, ``attrs`` will generate a ``__hash__`` for you.
2. If *cmp* is True and *frozen* is False, ``__hash__`` will be set to 2. If *eq* is True and *frozen* is False, ``__hash__`` will be set to
None, marking it unhashable (which it is). None, marking it unhashable (which it is).
3. If *cmp* is False, ``__hash__`` will be left untouched meaning the 3. If *eq* is False, ``__hash__`` will be left untouched meaning the
``__hash__`` method of the base class will be used (if base class is ``__hash__`` method of the base class will be used (if base class is
``object``, this means it will fall back to id-based hashing.). ``object``, this means it will fall back to id-based hashing.).
@ -767,29 +849,29 @@ def attrs(
didn't freeze it programmatically) by passing ``True`` or not. Both of didn't freeze it programmatically) by passing ``True`` or not. Both of
these cases are rather special and should be used carefully. these cases are rather special and should be used carefully.
See the `Python documentation \ See our documentation on `hashing`, Python's documentation on
<https://docs.python.org/3/reference/datamodel.html#object.__hash__>`_ `object.__hash__`, and the `GitHub issue that led to the default \
and the `GitHub issue that led to the default behavior \ behavior <https://github.com/python-attrs/attrs/issues/136>`_ for more
<https://github.com/python-attrs/attrs/issues/136>`_ for more details. details.
:type hash: ``bool`` or ``None`` :type hash: ``bool`` or ``None``
:param bool init: Create a ``__init__`` method that initializes the :param bool init: Create a ``__init__`` method that initializes the
``attrs`` attributes. Leading underscores are stripped for the ``attrs`` attributes. Leading underscores are stripped for the
argument name. If a ``__attrs_post_init__`` method exists on the argument name. If a ``__attrs_post_init__`` method exists on the
class, it will be called after the class is fully initialized. class, it will be called after the class is fully initialized.
:param bool slots: Create a slots_-style class that's more :param bool slots: Create a `slotted class <slotted classes>` that's more
memory-efficient. See :ref:`slots` for further ramifications. memory-efficient.
:param bool frozen: Make instances immutable after initialization. If :param bool frozen: Make instances immutable after initialization. If
someone attempts to modify a frozen instance, someone attempts to modify a frozen instance,
:exc:`attr.exceptions.FrozenInstanceError` is raised. `attr.exceptions.FrozenInstanceError` is raised.
Please note: Please note:
1. This is achieved by installing a custom ``__setattr__`` method 1. This is achieved by installing a custom ``__setattr__`` method
on your class so you can't implement an own one. on your class, so you can't implement your own.
2. True immutability is impossible in Python. 2. True immutability is impossible in Python.
3. This *does* have a minor a runtime performance :ref:`impact 3. This *does* have a minor a runtime performance `impact
<how-frozen>` when initializing new instances. In other words: <how-frozen>` when initializing new instances. In other words:
``__init__`` is slightly slower with ``frozen=True``. ``__init__`` is slightly slower with ``frozen=True``.
@ -798,24 +880,24 @@ def attrs(
circumvent that limitation by using circumvent that limitation by using
``object.__setattr__(self, "attribute_name", value)``. ``object.__setattr__(self, "attribute_name", value)``.
.. _slots: https://docs.python.org/3/reference/datamodel.html#slots
:param bool weakref_slot: Make instances weak-referenceable. This has no :param bool weakref_slot: Make instances weak-referenceable. This has no
effect unless ``slots`` is also enabled. effect unless ``slots`` is also enabled.
:param bool auto_attribs: If True, collect `PEP 526`_-annotated attributes :param bool auto_attribs: If True, collect `PEP 526`_-annotated attributes
(Python 3.6 and later only) from the class body. (Python 3.6 and later only) from the class body.
In this case, you **must** annotate every field. If ``attrs`` In this case, you **must** annotate every field. If ``attrs``
encounters a field that is set to an :func:`attr.ib` but lacks a type encounters a field that is set to an `attr.ib` but lacks a type
annotation, an :exc:`attr.exceptions.UnannotatedAttributeError` is annotation, an `attr.exceptions.UnannotatedAttributeError` is
raised. Use ``field_name: typing.Any = attr.ib(...)`` if you don't raised. Use ``field_name: typing.Any = attr.ib(...)`` if you don't
want to set a type. want to set a type.
If you assign a value to those attributes (e.g. ``x: int = 42``), that If you assign a value to those attributes (e.g. ``x: int = 42``), that
value becomes the default value like if it were passed using value becomes the default value like if it were passed using
``attr.ib(default=42)``. Passing an instance of :class:`Factory` also ``attr.ib(default=42)``. Passing an instance of `Factory` also
works as expected. works as expected.
Attributes annotated as :data:`typing.ClassVar` are **ignored**. Attributes annotated as `typing.ClassVar`, and attributes that are
neither annotated nor set to an `attr.ib` are **ignored**.
.. _`PEP 526`: https://www.python.org/dev/peps/pep-0526/ .. _`PEP 526`: https://www.python.org/dev/peps/pep-0526/
:param bool kw_only: Make all attributes keyword-only (Python 3+) :param bool kw_only: Make all attributes keyword-only (Python 3+)
@ -828,15 +910,15 @@ def attrs(
fields involved in hash code computation or mutations of the objects fields involved in hash code computation or mutations of the objects
those fields point to after object creation. If such changes occur, those fields point to after object creation. If such changes occur,
the behavior of the object's hash code is undefined. the behavior of the object's hash code is undefined.
:param bool auto_exc: If the class subclasses :class:`BaseException` :param bool auto_exc: If the class subclasses `BaseException`
(which implicitly includes any subclass of any exception), the (which implicitly includes any subclass of any exception), the
following happens to behave like a well-behaved Python exceptions following happens to behave like a well-behaved Python exceptions
class: class:
- the values for *cmp* and *hash* are ignored and the instances compare - the values for *eq*, *order*, and *hash* are ignored and the
and hash by the instance's ids (N.B. ``attrs`` will *not* remove instances compare and hash by the instance's ids (N.B. ``attrs`` will
existing implementations of ``__hash__`` or the equality methods. It *not* remove existing implementations of ``__hash__`` or the equality
just won't add own ones.), methods. It just won't add own ones.),
- all attributes that are either passed into ``__init__`` or have a - all attributes that are either passed into ``__init__`` or have a
default value are additionally available as a tuple in the ``args`` default value are additionally available as a tuple in the ``args``
attribute, attribute,
@ -855,13 +937,19 @@ def attrs(
.. versionadded:: 18.2.0 *weakref_slot* .. versionadded:: 18.2.0 *weakref_slot*
.. deprecated:: 18.2.0 .. deprecated:: 18.2.0
``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now raise a ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now raise a
:class:`DeprecationWarning` if the classes compared are subclasses of `DeprecationWarning` if the classes compared are subclasses of
each other. ``__eq`` and ``__ne__`` never tried to compared subclasses each other. ``__eq`` and ``__ne__`` never tried to compared subclasses
to each other. to each other.
.. versionchanged:: 19.2.0
``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now do not consider
subclasses comparable anymore.
.. versionadded:: 18.2.0 *kw_only* .. versionadded:: 18.2.0 *kw_only*
.. versionadded:: 18.2.0 *cache_hash* .. versionadded:: 18.2.0 *cache_hash*
.. versionadded:: 19.1.0 *auto_exc* .. versionadded:: 19.1.0 *auto_exc*
.. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01.
.. versionadded:: 19.2.0 *eq* and *order*
""" """
eq, order = _determine_eq_order(cmp, eq, order)
def wrap(cls): def wrap(cls):
@ -886,15 +974,17 @@ def attrs(
builder.add_repr(repr_ns) builder.add_repr(repr_ns)
if str is True: if str is True:
builder.add_str() builder.add_str()
if cmp is True and not is_exc: if eq is True and not is_exc:
builder.add_cmp() builder.add_eq()
if order is True and not is_exc:
builder.add_order()
if hash is not True and hash is not False and hash is not None: if hash is not True and hash is not False and hash is not None:
# Can't use `hash in` because 1 == True for example. # Can't use `hash in` because 1 == True for example.
raise TypeError( raise TypeError(
"Invalid value for hash. Must be True, False, or None." "Invalid value for hash. Must be True, False, or None."
) )
elif hash is False or (hash is None and cmp is False) or is_exc: elif hash is False or (hash is None and eq is False) or is_exc:
# Don't do anything. Should fall back to __object__'s __hash__ # Don't do anything. Should fall back to __object__'s __hash__
# which is by id. # which is by id.
if cache_hash: if cache_hash:
@ -903,7 +993,7 @@ def attrs(
" hashing must be either explicitly or implicitly " " hashing must be either explicitly or implicitly "
"enabled." "enabled."
) )
elif hash is True or (hash is None and cmp is True and frozen is True): elif hash is True or (hash is None and eq is True and frozen is True):
# Build a __hash__ if told so, or if it's safe. # Build a __hash__ if told so, or if it's safe.
builder.add_hash() builder.add_hash()
else: else:
@ -1005,9 +1095,7 @@ def _generate_unique_filename(cls, func_name):
def _make_hash(cls, attrs, frozen, cache_hash): def _make_hash(cls, attrs, frozen, cache_hash):
attrs = tuple( attrs = tuple(
a a for a in attrs if a.hash is True or (a.hash is None and a.eq is True)
for a in attrs
if a.hash is True or (a.hash is None and a.cmp is True)
) )
tab = " " tab = " "
@ -1085,14 +1173,8 @@ def __ne__(self, other):
return not result return not result
WARNING_CMP_ISINSTANCE = ( def _make_eq(cls, attrs):
"Comparision of subclasses using __%s__ is deprecated and will be removed " attrs = [a for a in attrs if a.eq]
"in 2019."
)
def _make_cmp(cls, attrs):
attrs = [a for a in attrs if a.cmp]
unique_filename = _generate_unique_filename(cls, "eq") unique_filename = _generate_unique_filename(cls, "eq")
lines = [ lines = [
@ -1127,8 +1209,11 @@ def _make_cmp(cls, attrs):
script.splitlines(True), script.splitlines(True),
unique_filename, unique_filename,
) )
eq = locs["__eq__"] return locs["__eq__"], __ne__
ne = __ne__
def _make_order(cls, attrs):
attrs = [a for a in attrs if a.order]
def attrs_to_tuple(obj): def attrs_to_tuple(obj):
""" """
@ -1140,67 +1225,49 @@ def _make_cmp(cls, attrs):
""" """
Automatically created by attrs. Automatically created by attrs.
""" """
if isinstance(other, self.__class__): if other.__class__ is self.__class__:
if other.__class__ is not self.__class__:
warnings.warn(
WARNING_CMP_ISINSTANCE % ("lt",), DeprecationWarning
)
return attrs_to_tuple(self) < attrs_to_tuple(other) return attrs_to_tuple(self) < attrs_to_tuple(other)
else:
return NotImplemented return NotImplemented
def __le__(self, other): def __le__(self, other):
""" """
Automatically created by attrs. Automatically created by attrs.
""" """
if isinstance(other, self.__class__): if other.__class__ is self.__class__:
if other.__class__ is not self.__class__:
warnings.warn(
WARNING_CMP_ISINSTANCE % ("le",), DeprecationWarning
)
return attrs_to_tuple(self) <= attrs_to_tuple(other) return attrs_to_tuple(self) <= attrs_to_tuple(other)
else:
return NotImplemented return NotImplemented
def __gt__(self, other): def __gt__(self, other):
""" """
Automatically created by attrs. Automatically created by attrs.
""" """
if isinstance(other, self.__class__): if other.__class__ is self.__class__:
if other.__class__ is not self.__class__:
warnings.warn(
WARNING_CMP_ISINSTANCE % ("gt",), DeprecationWarning
)
return attrs_to_tuple(self) > attrs_to_tuple(other) return attrs_to_tuple(self) > attrs_to_tuple(other)
else:
return NotImplemented return NotImplemented
def __ge__(self, other): def __ge__(self, other):
""" """
Automatically created by attrs. Automatically created by attrs.
""" """
if isinstance(other, self.__class__): if other.__class__ is self.__class__:
if other.__class__ is not self.__class__:
warnings.warn(
WARNING_CMP_ISINSTANCE % ("ge",), DeprecationWarning
)
return attrs_to_tuple(self) >= attrs_to_tuple(other) return attrs_to_tuple(self) >= attrs_to_tuple(other)
else:
return NotImplemented return NotImplemented
return eq, ne, __lt__, __le__, __gt__, __ge__ return __lt__, __le__, __gt__, __ge__
def _add_cmp(cls, attrs=None): def _add_eq(cls, attrs=None):
""" """
Add comparison methods to *cls*. Add equality methods to *cls* with *attrs*.
""" """
if attrs is None: if attrs is None:
attrs = cls.__attrs_attrs__ attrs = cls.__attrs_attrs__
cls.__eq__, cls.__ne__, cls.__lt__, cls.__le__, cls.__gt__, cls.__ge__ = _make_cmp( # noqa cls.__eq__, cls.__ne__ = _make_eq(cls, attrs)
cls, attrs
)
return cls return cls
@ -1210,9 +1277,17 @@ _already_repring = threading.local()
def _make_repr(attrs, ns): def _make_repr(attrs, ns):
""" """
Make a repr method for *attr_names* adding *ns* to the full name. Make a repr method that includes relevant *attrs*, adding *ns* to the full
name.
""" """
attr_names = tuple(a.name for a in attrs if a.repr)
# Figure out which attributes to include, and which function to use to
# format them. The a.repr value can be either bool or a custom callable.
attr_names_with_reprs = tuple(
(a.name, repr if a.repr is True else a.repr)
for a in attrs
if a.repr is not False
)
def __repr__(self): def __repr__(self):
""" """
@ -1244,12 +1319,14 @@ def _make_repr(attrs, ns):
try: try:
result = [class_name, "("] result = [class_name, "("]
first = True first = True
for name in attr_names: for name, attr_repr in attr_names_with_reprs:
if first: if first:
first = False first = False
else: else:
result.append(", ") result.append(", ")
result.extend((name, "=", repr(getattr(self, name, NOTHING)))) result.extend(
(name, "=", attr_repr(getattr(self, name, NOTHING)))
)
return "".join(result) + ")" return "".join(result) + ")"
finally: finally:
working_set.remove(id(self)) working_set.remove(id(self))
@ -1318,7 +1395,7 @@ def fields(cls):
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class. class.
:rtype: tuple (with name accessors) of :class:`attr.Attribute` :rtype: tuple (with name accessors) of `attr.Attribute`
.. versionchanged:: 16.2.0 Returned tuple allows accessing the fields .. versionchanged:: 16.2.0 Returned tuple allows accessing the fields
by name. by name.
@ -1345,7 +1422,7 @@ def fields_dict(cls):
class. class.
:rtype: an ordered dict where keys are attribute names and values are :rtype: an ordered dict where keys are attribute names and values are
:class:`attr.Attribute`\\ s. This will be a :class:`dict` if it's `attr.Attribute`\\ s. This will be a `dict` if it's
naturally ordered like on Python 3.6+ or an naturally ordered like on Python 3.6+ or an
:class:`~collections.OrderedDict` otherwise. :class:`~collections.OrderedDict` otherwise.
@ -1675,10 +1752,10 @@ class Attribute(object):
:attribute name: The name of the attribute. :attribute name: The name of the attribute.
Plus *all* arguments of :func:`attr.ib` (except for `factory` which is only Plus *all* arguments of `attr.ib` (except for ``factory``
syntactic sugar for ``default=Factory(...)``. which is only syntactic sugar for ``default=Factory(...)``.
For the version history of the fields, see :func:`attr.ib`. For the version history of the fields, see `attr.ib`.
""" """
__slots__ = ( __slots__ = (
@ -1686,7 +1763,8 @@ class Attribute(object):
"default", "default",
"validator", "validator",
"repr", "repr",
"cmp", "eq",
"order",
"hash", "hash",
"init", "init",
"metadata", "metadata",
@ -1701,14 +1779,18 @@ class Attribute(object):
default, default,
validator, validator,
repr, repr,
cmp, cmp, # XXX: unused, remove along with other cmp code.
hash, hash,
init, init,
metadata=None, metadata=None,
type=None, type=None,
converter=None, converter=None,
kw_only=False, kw_only=False,
eq=None,
order=None,
): ):
eq, order = _determine_eq_order(cmp, eq, order)
# Cache this descriptor here to speed things up later. # Cache this descriptor here to speed things up later.
bound_setattr = _obj_setattr.__get__(self, Attribute) bound_setattr = _obj_setattr.__get__(self, Attribute)
@ -1718,7 +1800,8 @@ class Attribute(object):
bound_setattr("default", default) bound_setattr("default", default)
bound_setattr("validator", validator) bound_setattr("validator", validator)
bound_setattr("repr", repr) bound_setattr("repr", repr)
bound_setattr("cmp", cmp) bound_setattr("eq", eq)
bound_setattr("order", order)
bound_setattr("hash", hash) bound_setattr("hash", hash)
bound_setattr("init", init) bound_setattr("init", init)
bound_setattr("converter", converter) bound_setattr("converter", converter)
@ -1761,9 +1844,19 @@ class Attribute(object):
validator=ca._validator, validator=ca._validator,
default=ca._default, default=ca._default,
type=type, type=type,
cmp=None,
**inst_dict **inst_dict
) )
@property
def cmp(self):
"""
Simulate the presence of a cmp attribute and warn.
"""
warnings.warn(_CMP_DEPRECATION, DeprecationWarning, stacklevel=2)
return self.eq and self.order
# Don't use attr.assoc since fields(Attribute) doesn't work # Don't use attr.assoc since fields(Attribute) doesn't work
def _assoc(self, **changes): def _assoc(self, **changes):
""" """
@ -1811,7 +1904,9 @@ _a = [
default=NOTHING, default=NOTHING,
validator=None, validator=None,
repr=True, repr=True,
cmp=True, cmp=None,
eq=True,
order=False,
hash=(name != "metadata"), hash=(name != "metadata"),
init=True, init=True,
) )
@ -1819,7 +1914,7 @@ _a = [
] ]
Attribute = _add_hash( Attribute = _add_hash(
_add_cmp(_add_repr(Attribute, attrs=_a), attrs=_a), _add_eq(_add_repr(Attribute, attrs=_a), attrs=_a),
attrs=[a for a in _a if a.hash], attrs=[a for a in _a if a.hash],
) )
@ -1837,7 +1932,8 @@ class _CountingAttr(object):
"counter", "counter",
"_default", "_default",
"repr", "repr",
"cmp", "eq",
"order",
"hash", "hash",
"init", "init",
"metadata", "metadata",
@ -1852,22 +1948,34 @@ class _CountingAttr(object):
default=NOTHING, default=NOTHING,
validator=None, validator=None,
repr=True, repr=True,
cmp=True, cmp=None,
hash=True, hash=True,
init=True, init=True,
kw_only=False, kw_only=False,
eq=True,
order=False,
)
for name in (
"counter",
"_default",
"repr",
"eq",
"order",
"hash",
"init",
) )
for name in ("counter", "_default", "repr", "cmp", "hash", "init")
) + ( ) + (
Attribute( Attribute(
name="metadata", name="metadata",
default=None, default=None,
validator=None, validator=None,
repr=True, repr=True,
cmp=True, cmp=None,
hash=False, hash=False,
init=True, init=True,
kw_only=False, kw_only=False,
eq=True,
order=False,
), ),
) )
cls_counter = 0 cls_counter = 0
@ -1877,13 +1985,15 @@ class _CountingAttr(object):
default, default,
validator, validator,
repr, repr,
cmp, cmp, # XXX: unused, remove along with cmp
hash, hash,
init, init,
converter, converter,
metadata, metadata,
type, type,
kw_only, kw_only,
eq,
order,
): ):
_CountingAttr.cls_counter += 1 _CountingAttr.cls_counter += 1
self.counter = _CountingAttr.cls_counter self.counter = _CountingAttr.cls_counter
@ -1894,7 +2004,8 @@ class _CountingAttr(object):
else: else:
self._validator = validator self._validator = validator
self.repr = repr self.repr = repr
self.cmp = cmp self.eq = eq
self.order = order
self.hash = hash self.hash = hash
self.init = init self.init = init
self.converter = converter self.converter = converter
@ -1934,7 +2045,7 @@ class _CountingAttr(object):
return meth return meth
_CountingAttr = _add_cmp(_add_repr(_CountingAttr)) _CountingAttr = _add_eq(_add_repr(_CountingAttr))
@attrs(slots=True, init=False, hash=True) @attrs(slots=True, init=False, hash=True)
@ -1942,7 +2053,7 @@ class Factory(object):
""" """
Stores a factory callable. Stores a factory callable.
If passed as the default value to :func:`attr.ib`, the factory is used to If passed as the default value to `attr.ib`, the factory is used to
generate a new value. generate a new value.
:param callable factory: A callable that takes either none or exactly one :param callable factory: A callable that takes either none or exactly one
@ -1975,15 +2086,15 @@ def make_class(name, attrs, bases=(object,), **attributes_arguments):
:param attrs: A list of names or a dictionary of mappings of names to :param attrs: A list of names or a dictionary of mappings of names to
attributes. attributes.
If *attrs* is a list or an ordered dict (:class:`dict` on Python 3.6+, If *attrs* is a list or an ordered dict (`dict` on Python 3.6+,
:class:`collections.OrderedDict` otherwise), the order is deduced from `collections.OrderedDict` otherwise), the order is deduced from
the order of the names or attributes inside *attrs*. Otherwise the the order of the names or attributes inside *attrs*. Otherwise the
order of the definition of the attributes is used. order of the definition of the attributes is used.
:type attrs: :class:`list` or :class:`dict` :type attrs: `list` or `dict`
:param tuple bases: Classes that the new class will subclass. :param tuple bases: Classes that the new class will subclass.
:param attributes_arguments: Passed unmodified to :func:`attr.s`. :param attributes_arguments: Passed unmodified to `attr.s`.
:return: A new class with *attrs*. :return: A new class with *attrs*.
:rtype: type :rtype: type
@ -2015,6 +2126,15 @@ def make_class(name, attrs, bases=(object,), **attributes_arguments):
except (AttributeError, ValueError): except (AttributeError, ValueError):
pass pass
# We do it here for proper warnings with meaningful stacklevel.
cmp = attributes_arguments.pop("cmp", None)
(
attributes_arguments["eq"],
attributes_arguments["order"],
) = _determine_eq_order(
cmp, attributes_arguments.get("eq"), attributes_arguments.get("order")
)
return _attrs(these=cls_dict, **attributes_arguments)(type_) return _attrs(these=cls_dict, **attributes_arguments)(type_)

85
lib/attr/_version_info.py

@ -0,0 +1,85 @@
from __future__ import absolute_import, division, print_function
from functools import total_ordering
from ._funcs import astuple
from ._make import attrib, attrs
@total_ordering
@attrs(eq=False, order=False, slots=True, frozen=True)
class VersionInfo(object):
"""
A version object that can be compared to tuple of length 1--4:
>>> attr.VersionInfo(19, 1, 0, "final") <= (19, 2)
True
>>> attr.VersionInfo(19, 1, 0, "final") < (19, 1, 1)
True
>>> vi = attr.VersionInfo(19, 2, 0, "final")
>>> vi < (19, 1, 1)
False
>>> vi < (19,)
False
>>> vi == (19, 2,)
True
>>> vi == (19, 2, 1)
False
.. versionadded:: 19.2
"""
year = attrib(type=int)
minor = attrib(type=int)
micro = attrib(type=int)
releaselevel = attrib(type=str)
@classmethod
def _from_version_string(cls, s):
"""
Parse *s* and return a _VersionInfo.
"""
v = s.split(".")
if len(v) == 3:
v.append("final")
return cls(
year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3]
)
def _ensure_tuple(self, other):
"""
Ensure *other* is a tuple of a valid length.
Returns a possibly transformed *other* and ourselves as a tuple of
the same length as *other*.
"""
if self.__class__ is other.__class__:
other = astuple(other)
if not isinstance(other, tuple):
raise NotImplementedError
if not (1 <= len(other) <= 4):
raise NotImplementedError
return astuple(self)[: len(other)], other
def __eq__(self, other):
try:
us, them = self._ensure_tuple(other)
except NotImplementedError:
return NotImplemented
return us == them
def __lt__(self, other):
try:
us, them = self._ensure_tuple(other)
except NotImplementedError:
return NotImplemented
# Since alphabetically "dev0" < "final" < "post1" < "post2", we don't
# have to do anything special with releaselevel for now.
return us < them

9
lib/attr/_version_info.pyi

@ -0,0 +1,9 @@
class VersionInfo:
@property
def year(self) -> int: ...
@property
def minor(self) -> int: ...
@property
def micro(self) -> int: ...
@property
def releaselevel(self) -> str: ...

4
lib/attr/converters.py

@ -32,14 +32,14 @@ def default_if_none(default=NOTHING, factory=None):
result of *factory*. result of *factory*.
:param default: Value to be used if ``None`` is passed. Passing an instance :param default: Value to be used if ``None`` is passed. Passing an instance
of :class:`attr.Factory` is supported, however the ``takes_self`` option of `attr.Factory` is supported, however the ``takes_self`` option
is *not*. is *not*.
:param callable factory: A callable that takes not parameters whose result :param callable factory: A callable that takes not parameters whose result
is used if ``None`` is passed. is used if ``None`` is passed.
:raises TypeError: If **neither** *default* or *factory* is passed. :raises TypeError: If **neither** *default* or *factory* is passed.
:raises TypeError: If **both** *default* and *factory* are passed. :raises TypeError: If **both** *default* and *factory* are passed.
:raises ValueError: If an instance of :class:`attr.Factory` is passed with :raises ValueError: If an instance of `attr.Factory` is passed with
``takes_self=True``. ``takes_self=True``.
.. versionadded:: 18.2.0 .. versionadded:: 18.2.0

2
lib/attr/converters.pyi

@ -4,7 +4,7 @@ from . import _ConverterType
_T = TypeVar("_T") _T = TypeVar("_T")
def optional( def optional(
converter: _ConverterType[_T] converter: _ConverterType[_T],
) -> _ConverterType[Optional[_T]]: ... ) -> _ConverterType[Optional[_T]]: ...
@overload @overload
def default_if_none(default: _T) -> _ConverterType[_T]: ... def default_if_none(default: _T) -> _ConverterType[_T]: ...

2
lib/attr/exceptions.py

@ -6,7 +6,7 @@ class FrozenInstanceError(AttributeError):
A frozen/immutable instance has been attempted to be modified. A frozen/immutable instance has been attempted to be modified.
It mirrors the behavior of ``namedtuples`` by using the same error message It mirrors the behavior of ``namedtuples`` by using the same error message
and subclassing :exc:`AttributeError`. and subclassing `AttributeError`.
.. versionadded:: 16.1.0 .. versionadded:: 16.1.0
""" """

10
lib/attr/filters.py

@ -1,5 +1,5 @@
""" """
Commonly useful filters for :func:`attr.asdict`. Commonly useful filters for `attr.asdict`.
""" """
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
@ -23,9 +23,9 @@ def include(*what):
Whitelist *what*. Whitelist *what*.
:param what: What to whitelist. :param what: What to whitelist.
:type what: :class:`list` of :class:`type` or :class:`attr.Attribute`\\ s :type what: `list` of `type` or `attr.Attribute`\\ s
:rtype: :class:`callable` :rtype: `callable`
""" """
cls, attrs = _split_what(what) cls, attrs = _split_what(what)
@ -40,9 +40,9 @@ def exclude(*what):
Blacklist *what*. Blacklist *what*.
:param what: What to blacklist. :param what: What to blacklist.
:type what: :class:`list` of classes or :class:`attr.Attribute`\\ s. :type what: `list` of classes or `attr.Attribute`\\ s.
:rtype: :class:`callable` :rtype: `callable`
""" """
cls, attrs = _split_what(what) cls, attrs = _split_what(what)

99
lib/attr/validators.py

@ -4,6 +4,8 @@ Commonly useful validators.
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
import re
from ._make import _AndValidator, and_, attrib, attrs from ._make import _AndValidator, and_, attrib, attrs
from .exceptions import NotCallableError from .exceptions import NotCallableError
@ -15,6 +17,7 @@ __all__ = [
"in_", "in_",
"instance_of", "instance_of",
"is_callable", "is_callable",
"matches_re",
"optional", "optional",
"provides", "provides",
] ]
@ -50,20 +53,92 @@ class _InstanceOfValidator(object):
def instance_of(type): def instance_of(type):
""" """
A validator that raises a :exc:`TypeError` if the initializer is called A validator that raises a `TypeError` if the initializer is called
with a wrong type for this particular attribute (checks are performed using with a wrong type for this particular attribute (checks are performed using
:func:`isinstance` therefore it's also valid to pass a tuple of types). `isinstance` therefore it's also valid to pass a tuple of types).
:param type: The type to check for. :param type: The type to check for.
:type type: type or tuple of types :type type: type or tuple of types
:raises TypeError: With a human readable error message, the attribute :raises TypeError: With a human readable error message, the attribute
(of type :class:`attr.Attribute`), the expected type, and the value it (of type `attr.Attribute`), the expected type, and the value it
got. got.
""" """
return _InstanceOfValidator(type) return _InstanceOfValidator(type)
@attrs(repr=False, frozen=True)
class _MatchesReValidator(object):
regex = attrib()
flags = attrib()
match_func = attrib()
def __call__(self, inst, attr, value):
"""
We use a callable class to be able to change the ``__repr__``.
"""
if not self.match_func(value):
raise ValueError(
"'{name}' must match regex {regex!r}"
" ({value!r} doesn't)".format(
name=attr.name, regex=self.regex.pattern, value=value
),
attr,
self.regex,
value,
)
def __repr__(self):
return "<matches_re validator for pattern {regex!r}>".format(
regex=self.regex
)
def matches_re(regex, flags=0, func=None):
r"""
A validator that raises `ValueError` if the initializer is called
with a string that doesn't match *regex*.
:param str regex: a regex string to match against
:param int flags: flags that will be passed to the underlying re function
(default 0)
:param callable func: which underlying `re` function to call (options
are `re.fullmatch`, `re.search`, `re.match`, default
is ``None`` which means either `re.fullmatch` or an emulation of
it on Python 2). For performance reasons, they won't be used directly
but on a pre-`re.compile`\ ed pattern.
.. versionadded:: 19.2.0
"""
fullmatch = getattr(re, "fullmatch", None)
valid_funcs = (fullmatch, None, re.search, re.match)
if func not in valid_funcs:
raise ValueError(
"'func' must be one of %s."
% (
", ".join(
sorted(
e and e.__name__ or "None" for e in set(valid_funcs)
)
),
)
)
pattern = re.compile(regex, flags)
if func is re.match:
match_func = pattern.match
elif func is re.search:
match_func = pattern.search
else:
if fullmatch:
match_func = pattern.fullmatch
else:
pattern = re.compile(r"(?:{})\Z".format(regex), flags)
match_func = pattern.match
return _MatchesReValidator(pattern, flags, match_func)
@attrs(repr=False, slots=True, hash=True) @attrs(repr=False, slots=True, hash=True)
class _ProvidesValidator(object): class _ProvidesValidator(object):
interface = attrib() interface = attrib()
@ -91,7 +166,7 @@ class _ProvidesValidator(object):
def provides(interface): def provides(interface):
""" """
A validator that raises a :exc:`TypeError` if the initializer is called A validator that raises a `TypeError` if the initializer is called
with an object that does not provide the requested *interface* (checks are with an object that does not provide the requested *interface* (checks are
performed using ``interface.providedBy(value)`` (see `zope.interface performed using ``interface.providedBy(value)`` (see `zope.interface
<https://zopeinterface.readthedocs.io/en/latest/>`_). <https://zopeinterface.readthedocs.io/en/latest/>`_).
@ -99,7 +174,7 @@ def provides(interface):
:param zope.interface.Interface interface: The interface to check for. :param zope.interface.Interface interface: The interface to check for.
:raises TypeError: With a human readable error message, the attribute :raises TypeError: With a human readable error message, the attribute
(of type :class:`attr.Attribute`), the expected interface, and the (of type `attr.Attribute`), the expected interface, and the
value it got. value it got.
""" """
return _ProvidesValidator(interface) return _ProvidesValidator(interface)
@ -129,7 +204,7 @@ def optional(validator):
:param validator: A validator (or a list of validators) that is used for :param validator: A validator (or a list of validators) that is used for
non-``None`` values. non-``None`` values.
:type validator: callable or :class:`list` of callables. :type validator: callable or `list` of callables.
.. versionadded:: 15.1.0 .. versionadded:: 15.1.0
.. versionchanged:: 17.1.0 *validator* can be a list of validators. .. versionchanged:: 17.1.0 *validator* can be a list of validators.
@ -164,15 +239,15 @@ class _InValidator(object):
def in_(options): def in_(options):
""" """
A validator that raises a :exc:`ValueError` if the initializer is called A validator that raises a `ValueError` if the initializer is called
with a value that does not belong in the options provided. The check is with a value that does not belong in the options provided. The check is
performed using ``value in options``. performed using ``value in options``.
:param options: Allowed options. :param options: Allowed options.
:type options: list, tuple, :class:`enum.Enum`, ... :type options: list, tuple, `enum.Enum`, ...
:raises ValueError: With a human readable error message, the attribute (of :raises ValueError: With a human readable error message, the attribute (of
type :class:`attr.Attribute`), the expected options, and the value it type `attr.Attribute`), the expected options, and the value it
got. got.
.. versionadded:: 17.1.0 .. versionadded:: 17.1.0
@ -204,14 +279,14 @@ class _IsCallableValidator(object):
def is_callable(): def is_callable():
""" """
A validator that raises a :class:`attr.exceptions.NotCallableError` A validator that raises a `attr.exceptions.NotCallableError` if the
if the initializer is called with a value for this particular attribute initializer is called with a value for this particular attribute
that is not callable. that is not callable.
.. versionadded:: 19.1.0 .. versionadded:: 19.1.0
:raises `attr.exceptions.NotCallableError`: With a human readable error :raises `attr.exceptions.NotCallableError`: With a human readable error
message containing the attribute (:class:`attr.Attribute`) name, message containing the attribute (`attr.Attribute`) name,
and the value it got. and the value it got.
""" """
return _IsCallableValidator() return _IsCallableValidator()

35
lib/attr/validators.pyi

@ -9,24 +9,51 @@ from typing import (
Tuple, Tuple,
Iterable, Iterable,
Mapping, Mapping,
Callable,
Match,
AnyStr,
overload,
) )
from . import _ValidatorType from . import _ValidatorType
_T = TypeVar("_T") _T = TypeVar("_T")
_I = TypeVar("_I", bound=Iterable[_T]) _T1 = TypeVar("_T1")
_T2 = TypeVar("_T2")
_T3 = TypeVar("_T3")
_I = TypeVar("_I", bound=Iterable)
_K = TypeVar("_K") _K = TypeVar("_K")
_V = TypeVar("_V") _V = TypeVar("_V")
_M = TypeVar("_V", bound=Mapping[_K, _V]) _M = TypeVar("_M", bound=Mapping)
# To be more precise on instance_of use some overloads.
# If there are more than 3 items in the tuple then we fall back to Any
@overload
def instance_of(type: Type[_T]) -> _ValidatorType[_T]: ...
@overload
def instance_of(type: Tuple[Type[_T]]) -> _ValidatorType[_T]: ...
@overload
def instance_of( def instance_of(
type: Union[Tuple[Type[_T], ...], Type[_T]] type: Tuple[Type[_T1], Type[_T2]]
) -> _ValidatorType[_T]: ... ) -> _ValidatorType[Union[_T1, _T2]]: ...
@overload
def instance_of(
type: Tuple[Type[_T1], Type[_T2], Type[_T3]]
) -> _ValidatorType[Union[_T1, _T2, _T3]]: ...
@overload
def instance_of(type: Tuple[type, ...]) -> _ValidatorType[Any]: ...
def provides(interface: Any) -> _ValidatorType[Any]: ... def provides(interface: Any) -> _ValidatorType[Any]: ...
def optional( def optional(
validator: Union[_ValidatorType[_T], List[_ValidatorType[_T]]] validator: Union[_ValidatorType[_T], List[_ValidatorType[_T]]]
) -> _ValidatorType[Optional[_T]]: ... ) -> _ValidatorType[Optional[_T]]: ...
def in_(options: Container[_T]) -> _ValidatorType[_T]: ... def in_(options: Container[_T]) -> _ValidatorType[_T]: ...
def and_(*validators: _ValidatorType[_T]) -> _ValidatorType[_T]: ... def and_(*validators: _ValidatorType[_T]) -> _ValidatorType[_T]: ...
def matches_re(
regex: AnyStr,
flags: int = ...,
func: Optional[
Callable[[AnyStr, AnyStr, int], Optional[Match[AnyStr]]]
] = ...,
) -> _ValidatorType[AnyStr]: ...
def deep_iterable( def deep_iterable(
member_validator: _ValidatorType[_T], member_validator: _ValidatorType[_T],
iterable_validator: Optional[_ValidatorType[_I]] = ..., iterable_validator: Optional[_ValidatorType[_I]] = ...,

Loading…
Cancel
Save