Skip to content
Back to top

# API Reference for the `attr` Namespace

Note

These are the traditional APIs whose creation predates type annotations. They are not deprecated, but we suggest using the `attrs` namespace for new code, because they look nicer and have better defaults.

See also On The Core API Names.

## Core

attr.s(these=None, repr_ns=None, repr=None, cmp=None, hash=None, init=None, slots=False, frozen=False, weakref_slot=True, str=False, auto_attribs=False, kw_only=False, cache_hash=False, auto_exc=False, eq=None, order=None, auto_detect=False, collect_by_mro=False, getstate_setstate=None, on_setattr=None, field_transformer=None, match_args=True, unsafe_hash=None)

  A class decorator that adds dunder methods according to the specified attributes using `attr.ib` or the these argument.

  Consider using `attrs.define` / `attrs.frozen` in new code (`attr.s` will never go away, though).

  Parameters:

    repr_ns (str) – When using nested classes, there was no way in Python 2 to automatically detect that. This argument allows to set a custom name for a more meaningful `repr` output. This argument is pointless in Python 3 and is therefore deprecated.

  Caution

  Refer to `attrs.define` for the rest of the parameters, but note that they can have different defaults.

  Notably, leaving on_setattr as `None` will not add any hooks.

  Added in version 16.0.0: slots

  Added in version 16.1.0: frozen

  Added in version 16.3.0: str

  Added in version 16.3.0: Support for `__attrs_post_init__`.

  Changed in version 17.1.0: hash supports `None` as value which is also the default now.

  Added in version 17.3.0: auto_attribs

  Changed in version 18.1.0: If these is passed, no attributes are deleted from the class body.

  Changed in version 18.1.0: If these is ordered, the order is retained.

  Added in version 18.2.0: weakref_slot

  Deprecated since version 18.2.0: `__lt__`, `__le__`, `__gt__`, and `__ge__` now raise a `DeprecationWarning` if the classes compared are subclasses of each other. `__eq` and `__ne__` never tried to compared subclasses to each other.

  Changed in version 19.2.0: `__lt__`, `__le__`, `__gt__`, and `__ge__` now do not consider subclasses comparable anymore.

  Added in version 18.2.0: kw_only

  Added in version 18.2.0: cache_hash

  Added in version 19.1.0: auto_exc

  Deprecated since version 19.2.0: cmp Removal on or after 2021-06-01.

  Added in version 19.2.0: eq and order

  Added in version 20.1.0: auto_detect

  Added in version 20.1.0: collect_by_mro

  Added in version 20.1.0: getstate_setstate

  Added in version 20.1.0: on_setattr

  Added in version 20.3.0: field_transformer

  Changed in version 21.1.0: `init=False` injects `__attrs_init__`

  Changed in version 21.1.0: Support for `__attrs_pre_init__`

  Changed in version 21.1.0: cmp undeprecated

  Added in version 21.3.0: match_args

  Added in version 22.2.0: unsafe_hash as an alias for hash (for PEP 681 compliance).

  Deprecated since version 24.1.0: repr_ns

  Changed in version 24.1.0: Instances are not compared as tuples of attributes anymore, but using a big `and` condition. This is faster and has more correct behavior for uncomparable values like `math.nan`.

  Added in version 24.1.0: If a class has an inherited classmethod called `__attrs_init_subclass__`, it is executed after the class is created.

  Deprecated since version 24.1.0: hash is deprecated in favor of unsafe_hash.

  Changed in version 25.4.0: kw_only now only applies to attributes defined in the current class, and respects attribute-level `kw_only=False` settings.

  Added in version 25.4.0: force_kw_only

  For example:

      >>> import attr
      >>> @attr.s
      ... class C:
      ...     _private = attr.ib()
      >>> C(private=42)
      C(_private=42)
      >>> class D:
      ...     def __init__(self, x):
      ...         self.x = x
      >>> D(1)
      <D object at ...>
      >>> D = attr.s(these={"x": attr.ib()}, init=False)(D)
      >>> D(1)
      D(x=1)
      >>> @attr.s(auto_exc=True)
      ... class Error(Exception):
      ...     x = attr.ib()
      ...     y = attr.ib(default=42, init=False)
      >>> Error("foo")
      Error(x='foo', y=42)
      >>> raise Error("foo")
      Traceback (most recent call last):
         ...
      Error: ('foo', 42)
      >>> raise ValueError("foo", 42)   # for comparison
      Traceback (most recent call last):
         ...
      ValueError: ('foo', 42)

attr.ib(default=NOTHING, validator=None, repr=True, cmp=None, hash=None, init=True, metadata=None, type=None, converter=None, factory=None, kw_only=None, eq=None, order=None, on_setattr=None, alias=None)

  Create a new field / attribute on a class.

  Identical to `attrs.field`, except it’s not keyword-only.

  Consider using `attrs.field` in new code (`attr.ib` will never go away, though).

  Warning

  Does nothing unless the class is also decorated with `attr.s` (or similar)!

  Added in version 15.2.0: convert

  Added in version 16.3.0: metadata

  Changed in version 17.1.0: validator can be a `list` now.

  Changed in version 17.1.0: hash is `None` and therefore mirrors eq by default.

  Added in version 17.3.0: type

  Deprecated since version 17.4.0: convert

  Added in version 17.4.0: converter as a replacement for the deprecated convert to achieve consistency with other noun-based arguments.

  Added in version 18.1.0: `factory=f` is syntactic sugar for `default=attr.Factory(f)`.

  Added in version 18.2.0: kw_only

  Changed in version 19.2.0: convert keyword argument removed.

  Changed in version 19.2.0: repr also accepts a custom callable.

  Deprecated since version 19.2.0: cmp Removal on or after 2021-06-01.

  Added in version 19.2.0: eq and order

  Added in version 20.1.0: on_setattr

  Changed in version 20.3.0: kw_only backported to Python 2

  Changed in version 21.1.0: eq, order, and cmp also accept a custom callable

  Changed in version 21.1.0: cmp undeprecated

  Added in version 22.2.0: alias

  Changed in version 25.4.0: kw_only can now be None, and its default is also changed from False to None.

  Note

  attrs also comes with a serious-business alias `attr.attrib`.

  The object returned by `attr.ib` also allows for setting the default and the validator using decorators:

      >>> @attr.s
      ... class C:
      ...     x = attr.ib()
      ...     y = attr.ib()
      ...     @x.validator
      ...     def _any_name_except_a_name_of_an_attribute(self, attribute, value):
      ...         if value < 0:
      ...             raise ValueError("x must be positive")
      ...     @y.default
      ...     def _any_name_except_a_name_of_an_attribute(self):
      ...         return self.x + 1
      >>> C(1)
      C(x=1, y=2)
      >>> C(-1)
      Traceback (most recent call last):
          ...
      ValueError: x must be positive

attr.attrs()

  Serious business alias for `attr.s`.

attr.define()

  Same as `attrs.define`.

attr.mutable()

  Same as `attrs.mutable`.

attr.frozen()

  Same as `attrs.frozen`.

attr.field()

  Same as `attrs.field`.

class attr.Attribute

  Same as `attrs.Attribute`.

attr.make_class()

  Same as `attrs.make_class`.

class attr.Factory(factory, takes_self=False)

  Stores a factory callable.

  If passed as the default value to `attrs.field`, the factory is used to generate a new value.

  Parameters:

    - factory (Callable) – A callable that takes either none or exactly one mandatory positional argument depending on takes_self.

    - takes_self (bool) – Pass the partially initialized instance that is being initialized as a positional argument.

  Added in version 17.1.0: takes_self

  Same as `attrs.Factory`.

attr.NOTHING

  Same as `attrs.NOTHING`.

## Exceptions

All exceptions are available from both `attr.exceptions` and `attrs.exceptions` (it’s the same module in a different namespace).

Please refer to `attrs.exceptions` for details.

## Helpers

attr.cmp_using()

  Same as `attrs.cmp_using`.

attr.fields()

  Same as `attrs.fields`.

attr.fields_dict()

  Same as `attrs.fields_dict`.

attr.has()

  Same as `attrs.has`.

attr.resolve_types()

  Same as `attrs.resolve_types`.

attr.asdict(inst, recurse=True, filter=None, dict_factory=<class 'dict'>, retain_collection_types=False, value_serializer=None)

  Return the attrs attribute values of inst as a dict.

  Optionally recurse into other attrs-decorated classes.

  Parameters:

    - inst – Instance of an attrs-decorated class.

    - recurse (bool) – Recurse into classes that are also attrs-decorated.

    - filter (Callable) – A callable whose return code determines whether an attribute or element is included (`True`) or dropped (`False`). Is called with the `attrs.Attribute` as the first argument and the value as the second argument.

    - dict_factory (Callable) – A callable to produce dictionaries from. For example, to produce ordered dictionaries instead of normal Python dictionaries, pass in `collections.OrderedDict`.

    - retain_collection_types (bool) – Do not convert to `list` when encountering an attribute whose type is `tuple` or `set`. Only meaningful if recurse is `True`.

    - value_serializer (Callable | None) – A hook that is called for every attribute or dict key/value. It receives the current instance, field and value and must return the (updated) value. The hook is run after the optional filter has been applied.

  Returns:

    Return type of dict_factory.

  Raises:

    attrs.exceptions.NotAnAttrsClassError – If cls is not an attrs class.

  Added in version 16.0.0: dict_factory

  Added in version 16.1.0: retain_collection_types

  Added in version 20.3.0: value_serializer

  Added in version 21.3.0: If a dict has a collection for a key, it is serialized as a tuple.

attr.astuple(inst, recurse=True, filter=None, tuple_factory=<class 'tuple'>, retain_collection_types=False)

  Return the attrs attribute values of inst as a tuple.

  Optionally recurse into other attrs-decorated classes.

  Parameters:

    - inst – Instance of an attrs-decorated class.

    - recurse (bool) – Recurse into classes that are also attrs-decorated.

    - filter (Callable) – A callable whose return code determines whether an attribute or element is included (`True`) or dropped (`False`). Is called with the `attrs.Attribute` as the first argument and the value as the second argument.

    - tuple_factory (Callable) – A callable to produce tuples from. For example, to produce lists instead of tuples.

    - retain_collection_types (bool) – Do not convert to `list` or `dict` when encountering an attribute which type is `tuple`, `dict` or `set`. Only meaningful if recurse is `True`.

  Returns:

    Return type of tuple_factory

  Raises:

    attrs.exceptions.NotAnAttrsClassError – If cls is not an attrs class.

  Added in version 16.2.0.

attr.filters.include()

  Same as `attrs.filters.include`.

attr.filters.exclude()

  Same as `attrs.filters.exclude`.

See `attrs.asdict()` for examples.

All objects from `attrs.filters` are also available in `attr.filters`.

attr.evolve()

  Same as `attrs.evolve`.

attr.validate()

  Same as `attrs.validate`.

## Validators

All objects from `attrs.validators` are also available in `attr.validators`. Please refer to the former for details.

## Converters

All objects from `attrs.converters` are also available from `attr.converters`. Please refer to the former for details.

## Setters

All objects from `attrs.setters` are also available in `attr.setters`. Please refer to the former for details.

## Deprecated APIs

To help you write backward compatible code that doesn’t throw warnings on modern releases, the `attr` module has an `__version_info__` attribute as of version 19.2.0. It behaves similarly to `sys.version_info` and is an instance of `attr.VersionInfo`:

class attr.VersionInfo(year: int, minor: int, micro: int, releaselevel: str)

  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

  Added in version 19.2.

  With its help you can write code like this:

      >>> if getattr(attr, "__version_info__", (0,)) >= (19, 2):
      ...     cmp_off = {"eq": False}
      ... else:
      ...     cmp_off = {"cmp": False}
      >>> cmp_off == {"eq":  False}
      True
      >>> @attr.s(**cmp_off)
      ... class C:
      ...     pass

attr.assoc(inst, **changes)

  Copy inst and apply changes.

  This is different from `evolve` that applies the changes to the arguments that create the new instance.

  `evolve`’s behavior is preferable, but there are edge cases where it doesn’t work. Therefore `assoc` is deprecated, but will not be removed.

  Parameters:

    - inst – Instance of a class with attrs attributes.

    - changes – Keyword changes in the new copy.

  Returns:

    A copy of inst with changes incorporated.

  Raises:

    - attrs.exceptions.AttrsAttributeNotFoundError – If attr_name couldn’t be found on cls.

    - attrs.exceptions.NotAnAttrsClassError – If cls is not an attrs class.

  Deprecated since version 17.1.0: Use `attrs.evolve` instead if you can. This function will not be removed du to the slightly different approach compared to `attrs.evolve`, though.

Before attrs got `attrs.validators.set_disabled` and `attrs.validators.set_disabled`, it had the following APIs to globally enable and disable validators. They won’t be removed, but are discouraged to use:

attr.set_run_validators(run)

  Set whether or not validators are run. By default, they are run.

  Deprecated since version 21.3.0: It will not be removed, but it also will not be moved to new `attrs` namespace. Use `attrs.validators.set_disabled()` instead.

attr.get_run_validators()

  Return whether or not validators are run.

  Deprecated since version 21.3.0: It will not be removed, but it also will not be moved to new `attrs` namespace. Use `attrs.validators.get_disabled()` instead.

The serious-business aliases used to be called `attr.attributes` and `attr.attr`. There are no plans to remove them but they shouldn’t be used in new code.