attrs#

asdict(inst, *, recurse=True, filter=None, value_serializer=None)[source]#

Same as attr.asdict, except that collections types are always retained and dict is always used as dict_factory.

Added in version 21.3.0.

assoc(inst, **changes)[source]#

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.

astuple(inst, *, recurse=True, filter=None)[source]#

Same as attr.astuple, except that collections types are always retained and tuple is always used as the tuple_factory.

Added in version 21.3.0.

class Attribute[source]#

Read-only representation of an attribute.

Warning

You should never instantiate this class yourself.

The class has all arguments of attr.ib (except for factory which is only syntactic sugar for default=Factory(...) plus the following:

  • name (str): The name of the attribute.

  • alias (str): The __init__ parameter name of the attribute, after any explicit overrides and default private-attribute-name handling.

  • inherited (bool): Whether or not that attribute has been inherited from a base class.

  • eq_key and order_key (typing.Callable or None): The callables that are used for comparing and ordering objects by this attribute, respectively. These are set by passing a callable to attr.ib’s eq, order, or cmp arguments. See also comparison customization.

Instances of this class are frequently used for introspection purposes like:

  • fields returns a tuple of them.

  • Validators get them passed as the first argument.

  • The field transformer hook receives a list of them.

  • The alias property exposes the __init__ parameter name of the field, with any overrides and default private-attribute handling applied.

Added in version 20.1.0: inherited

Added in version 20.1.0: on_setattr

Changed in version 20.2.0: inherited is not taken into account for equality checks and hashing anymore.

Added in version 21.1.0: eq_key and order_key

Added in version 22.2.0: alias

For the full version history of the fields, see attr.ib.

__init__(name, default, validator, repr, cmp, hash, init, inherited, metadata=None, type=None, converter=None, kw_only=False, eq=None, eq_key=None, order=None, order_key=None, on_setattr=None, alias=None)[source]#
classmethod from_counting_attr(name, ca, type=None)[source]#
evolve(**changes)[source]#

Copy self and apply changes.

This works similarly to attrs.evolve but that function does not work with Attribute.

It is mainly meant to be used for transform-fields.

Added in version 20.3.0.

__getstate__()[source]#

Play nice with pickle.

__setstate__(state)[source]#

Play nice with pickle.

name#
default#
validator#
repr#
eq#
eq_key#
order#
order_key#
hash#
init#
metadata#
type#
converter#
kw_only#
inherited#
on_setattr#
alias#
class AttrsInstance[source]#
__init__(*args, **kwargs)#
cmp_using(eq=None, lt=None, le=None, gt=None, ge=None, require_same_type=True, class_name='Comparable')[source]#

Create a class that can be passed into attrs.field’s eq, order, and cmp arguments to customize field comparison.

The resulting class will have a full set of ordering methods if at least one of {lt, le, gt, ge} and eq are provided.

Parameters:
  • eq (Optional[callable]) – callable used to evaluate equality of two objects.

  • lt (Optional[callable]) – callable used to evaluate whether one object is less than another object.

  • le (Optional[callable]) – callable used to evaluate whether one object is less than or equal to another object.

  • gt (Optional[callable]) – callable used to evaluate whether one object is greater than another object.

  • ge (Optional[callable]) – callable used to evaluate whether one object is greater than or equal to another object.

  • require_same_type (bool) – When True, equality and ordering methods will return NotImplemented if objects are not of the same type.

  • class_name (Optional[str]) – Name of class. Defaults to β€˜Comparable’.

See comparison for more details.

Added in version 21.1.0.

define(maybe_cls=None, *, these=None, repr=None, unsafe_hash=None, hash=None, init=None, slots=True, frozen=False, weakref_slot=True, str=False, auto_attribs=None, kw_only=False, cache_hash=False, auto_exc=True, eq=None, order=False, auto_detect=True, getstate_setstate=None, on_setattr=None, field_transformer=None, match_args=True)[source]#

Define an attrs class.

Differences to the classic attr.s that it uses underneath:

  • Automatically detect whether or not auto_attribs should be True (c.f. auto_attribs parameter).

  • Converters and validators run when attributes are set by default – if frozen is False.

  • slots=True

    Caution

    Usually this has only upsides and few visible effects in everyday programming. But it can lead to some surprising behaviors, so please make sure to read slotted classes.

  • auto_exc=True

  • auto_detect=True

  • order=False

  • Some options that were only relevant on Python 2 or were kept around for backwards-compatibility have been removed.

Please note that these are all defaults and you can change them as you wish.

Parameters:

auto_attribs (Optional[bool]) –

If set to True or False, it behaves exactly like attr.s. If left None, attr.s will try to guess:

  1. If any attributes are annotated and no unannotated attrs.fieldss are found, it assumes auto_attribs=True.

  2. Otherwise it assumes auto_attribs=False and tries to collect attrs.fieldss.

For now, please refer to attr.s for the rest of the parameters.

Added in version 20.1.0.

Changed in version 21.3.0: Converters are also run on_setattr.

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

evolve(*args, **changes)[source]#

Create a new instance, based on the first positional argument with changes applied.

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:
  • TypeError – If attr_name couldn’t be found in the class __init__.

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

Added in version 17.1.0.

Deprecated since version 23.1.0: It is now deprecated to pass the instance using the keyword argument inst. It will raise a warning until at least April 2024, after which it will become an error. Always pass the instance as a positional argument.

class Factory[source]#

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

__init__(factory, takes_self=False)[source]#
factory#
takes_self#
__getstate__()[source]#

Play nice with pickle.

__setstate__(state)[source]#

Play nice with pickle.

field(*, default=NOTHING, validator=None, repr=True, hash=None, init=True, metadata=None, type=None, converter=None, factory=None, kw_only=False, eq=None, order=None, on_setattr=None, alias=None)[source]#

Identical to attr.ib, except keyword-only and with some arguments removed.

Added in version 23.1.0: The type parameter has been re-added; mostly for attrs.make_class. Please note that type checkers ignore this metadata.

Added in version 20.1.0.

fields_dict(cls)[source]#

Return an ordered dictionary of attrs attributes for a class, whose keys are the attribute names.

Parameters:

cls (type) – Class to introspect.

Raises:
  • TypeError – If cls is not a class.

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

Return type:

dict

Added in version 18.1.0.

fields(cls)[source]#

Return the tuple of attrs attributes for a class.

The tuple also allows accessing the fields by their names (see below for examples).

Parameters:

cls (type) – Class to introspect.

Raises:
  • TypeError – If cls is not a class.

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

Return type:

tuple (with name accessors) of attrs.Attribute

Changed in version 16.2.0: Returned tuple allows accessing the fields by name.

Changed in version 23.1.0: Add support for generic classes.

frozen(maybe_cls=None, *, these=None, repr=None, unsafe_hash=None, hash=None, init=None, slots=True, frozen=True, weakref_slot=True, str=False, auto_attribs=None, kw_only=False, cache_hash=False, auto_exc=True, eq=None, order=False, auto_detect=True, getstate_setstate=None, on_setattr=None, field_transformer=None, match_args=True)#

Define an attrs class.

Differences to the classic attr.s that it uses underneath:

  • Automatically detect whether or not auto_attribs should be True (c.f. auto_attribs parameter).

  • Converters and validators run when attributes are set by default – if frozen is False.

  • slots=True

    Caution

    Usually this has only upsides and few visible effects in everyday programming. But it can lead to some surprising behaviors, so please make sure to read slotted classes.

  • auto_exc=True

  • auto_detect=True

  • order=False

  • Some options that were only relevant on Python 2 or were kept around for backwards-compatibility have been removed.

Please note that these are all defaults and you can change them as you wish.

Parameters:

auto_attribs (Optional[bool]) –

If set to True or False, it behaves exactly like attr.s. If left None, attr.s will try to guess:

  1. If any attributes are annotated and no unannotated attrs.fieldss are found, it assumes auto_attribs=True.

  2. Otherwise it assumes auto_attribs=False and tries to collect attrs.fieldss.

For now, please refer to attr.s for the rest of the parameters.

Added in version 20.1.0.

Changed in version 21.3.0: Converters are also run on_setattr.

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

has(cls)[source]#

Check whether cls is a class with attrs attributes.

Parameters:

cls (type) – Class to introspect.

Raises:

TypeError – If cls is not a class.

Return type:

bool

make_class(name, attrs, bases=(<class 'object'>, ), class_body=None, **attributes_arguments)[source]#

A quick way to create a new class called name with attrs.

Parameters:
  • name (str) – The name for the new class.

  • attrs (list or dict) –

    A list of names or a dictionary of mappings of names to attr.ibs / attrs.fields.

    The order is deduced from the order of the names or attributes inside attrs. Otherwise the order of the definition of the attributes is used.

  • bases (tuple) – Classes that the new class will subclass.

  • class_body (dict) – An optional dictionary of class attributes for the new class.

  • attributes_arguments – Passed unmodified to attr.s.

Returns:

A new class with attrs.

Return type:

type

Added in version 17.1.0: bases

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

Changed in version 23.2.0: class_body

mutable(maybe_cls=None, *, these=None, repr=None, unsafe_hash=None, hash=None, init=None, slots=True, frozen=False, weakref_slot=True, str=False, auto_attribs=None, kw_only=False, cache_hash=False, auto_exc=True, eq=None, order=False, auto_detect=True, getstate_setstate=None, on_setattr=None, field_transformer=None, match_args=True)#

Define an attrs class.

Differences to the classic attr.s that it uses underneath:

  • Automatically detect whether or not auto_attribs should be True (c.f. auto_attribs parameter).

  • Converters and validators run when attributes are set by default – if frozen is False.

  • slots=True

    Caution

    Usually this has only upsides and few visible effects in everyday programming. But it can lead to some surprising behaviors, so please make sure to read slotted classes.

  • auto_exc=True

  • auto_detect=True

  • order=False

  • Some options that were only relevant on Python 2 or were kept around for backwards-compatibility have been removed.

Please note that these are all defaults and you can change them as you wish.

Parameters:

auto_attribs (Optional[bool]) –

If set to True or False, it behaves exactly like attr.s. If left None, attr.s will try to guess:

  1. If any attributes are annotated and no unannotated attrs.fieldss are found, it assumes auto_attribs=True.

  2. Otherwise it assumes auto_attribs=False and tries to collect attrs.fieldss.

For now, please refer to attr.s for the rest of the parameters.

Added in version 20.1.0.

Changed in version 21.3.0: Converters are also run on_setattr.

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

resolve_types(cls, globalns=None, localns=None, attribs=None, include_extras=True)[source]#

Resolve any strings and forward annotations in type annotations.

This is only required if you need concrete types in Attribute’s type field. In other words, you don’t need to resolve your types if you only use them for static type checking.

With no arguments, names will be looked up in the module in which the class was created. If this is not what you want, e.g. if the name only exists inside a method, you may pass globalns or localns to specify other dictionaries in which to look up these names. See the docs of typing.get_type_hints for more details.

Parameters:
  • cls (type) – Class to resolve.

  • globalns (Optional[dict]) – Dictionary containing global variables.

  • localns (Optional[dict]) – Dictionary containing local variables.

  • attribs (Optional[list]) – List of attribs for the given class. This is necessary when calling from inside a field_transformer since cls is not an attrs class yet.

  • include_extras (bool) – Resolve more accurately, if possible. Pass include_extras to typing.get_hints, if supported by the typing module. On supported Python versions (3.9+), this resolves the types more accurately.

Raises:
  • TypeError – If cls is not a class.

  • attrs.exceptions.NotAnAttrsClassError – If cls is not an attrs class and you didn’t pass any attribs.

  • NameError – If types cannot be resolved because of missing variables.

Returns:

cls so you can use this function also as a class decorator. Please note that you have to apply it after attrs.define. That means the decorator has to come in the line before attrs.define.

Added in version 20.1.0.

Added in version 21.1.0: attribs

Added in version 23.1.0: include_extras

validate(inst)[source]#

Validate all attributes on inst that have a validator.

Leaves all exceptions through.

Parameters:

inst – Instance of a class with attrs attributes.