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.
Args:
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.
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.
A class decorator that adds dunder methods according to
fields specified using type annotations,
field() calls, or the these argument.
Since attrs patches or replaces an existing class, you cannot use
object.__init_subclass__ with attrs classes, because it runs too early.
As a replacement, you can define __attrs_init_subclass__ on your class.
It will be called by attrs classes that subclass it after they’re
created. See also init-subclass.
Args:
slots (bool):
Create a slotted class that’s more
memory-efficient. Slotted classes are generally superior to the
default dict classes, but have some gotchas you should know about,
so we encourage you to read the glossary entry.
auto_detect (bool):
Instead of setting the init, repr, eq, and hash arguments
explicitly, assume they are set to True unless any of the
involved methods for one of the arguments is implemented in the
current class (meaning, it is not inherited from some base
class).
So, for example by implementing __eq__ on a class yourself,
attrs will deduce eq=False and will create neither__eq__nor__ne__ (but Python classes come with a
sensible __ne__ by default, so it should be enough to only
implement __eq__ in most cases).
Passing True or False` to init, repr, eq, cmp, or hash
overrides whatever auto_detect would determine.
auto_exc (bool):
If the class subclasses BaseException (which implicitly includes
any subclass of any exception), the following happens to behave
like a well-behaved Python exception class:
the values for eq, order, and hash are ignored and the
instances compare and hash by the instance’s ids [1] ,
all attributes that are either passed into __init__ or have a
default value are additionally available as a tuple in the
args attribute,
the value of str is ignored leaving __str__ to base
classes.
A callable that is run whenever the user attempts to set an
attribute (either by assignment like i.x=42 or by using
setattr like setattr(i,"x",42)). It receives the same
arguments as validators: the instance, the attribute that is being
modified, and the new value.
If no exception is raised, the attribute is set to the return value
of the callable.
If a list of callables is passed, they’re automatically wrapped in
an attrs.setters.pipe.
If left None, the default behavior is to run converters and
validators whenever an attribute is set.
init (bool):
Create a __init__ method that initializes the attrs
attributes. Leading underscores are stripped for the argument name,
unless an alias is set on the attribute.
See also
init shows advanced ways to customize the generated
__init__ method, including executing code before and after.
repr(bool):
Create a __repr__ method with a human readable representation
of attrs attributes.
str (bool):
Create a __str__ method that is identical to __repr__. This
is usually not necessary except for Exceptions.
eq (bool | None):
If True or None (default), add __eq__ and __ne__ methods
that check two instances for equality.
See also
comparison describes how to customize the comparison behavior
going as far comparing NumPy arrays.
order (bool | None):
If True, add __lt__, __le__, __gt__, and __ge__
methods that behave like eq above and allow instances to be
ordered.
They compare the instances as if they were tuples of their attrs
attributes if and only if the types of both classes are
identical.
If None mirror value of eq.
See also
comparison
cmp (bool | None):
Setting cmp is equivalent to setting eq and order to the same
value. Must not be mixed with eq or order.
unsafe_hash (bool | None):
If None (default), the __hash__ method is generated according
how eq and frozen are set.
If both are True, attrs will generate a __hash__ for
you.
If eq is True and frozen is False, __hash__ will be set
to None, marking it unhashable (which it is).
If eq is False, __hash__ will be left untouched meaning
the __hash__ method of the base class will be used. If the
base class is object, this means it will fall back to id-based
hashing.
Although not recommended, you can decide for yourself and force
attrs to create one (for example, if the class is immutable even
though you didn’t freeze it programmatically) by passing True or
not. Both of these cases are rather special and should be used
carefully.
Deprecated alias for unsafe_hash. unsafe_hash takes precedence.
cache_hash (bool):
Ensure that the object’s hash code is computed only once and stored
on the object. If this is set to True, hashing must be either
explicitly or implicitly enabled for this class. If the hash code
is cached, avoid any reassignments of fields involved in hash code
computation or mutations of the objects those fields point to after
object creation. If such changes occur, the behavior of the
object’s hash code is undefined.
frozen (bool):
Make instances immutable after initialization. If someone attempts
to modify a frozen instance, attrs.exceptions.FrozenInstanceError
is raised.
Note
This is achieved by installing a custom __setattr__
method on your class, so you can’t implement your own.
True immutability is impossible in Python.
This does have a minor a runtime performance impact
<how-frozen> when initializing new instances. In other
words: __init__ is slightly slower with frozen=True.
If a class is frozen, you cannot modify self in
__attrs_post_init__ or a self-written __init__. You
can circumvent that limitation by using
object.__setattr__(self,"attribute_name",value).
Subclasses of a frozen class are frozen too.
kw_only (bool):
Make all attributes keyword-only in the generated __init__ (if
init is False, this parameter is ignored).
weakref_slot (bool):
Make instances weak-referenceable. This has no effect unless
slots is True.
field_transformer (~typing.Callable | None):
A function that is called with the original class object and all
fields right before attrs finalizes the class. You can use this,
for example, to automatically add converters or validators to
fields based on their types.
See also
transform-fields
match_args (bool):
If True (default), set __match_args__ on the class to support
PEP 634 (Structural Pattern Matching). It is a tuple of all
non-keyword-only __init__ parameter names on Python 3.10 and
later. Ignored on older Python versions.
collect_by_mro (bool):
If True, attrs collects attributes from base classes correctly
according to the method resolution order. If False, attrs
will mimic the (wrong) behavior of dataclasses and PEP 681.
This is usually only interesting for slotted classes and you
should probably just set auto_detect to True.
If True, __getstate__ and __setstate__ are generated and
attached to the class. This is necessary for slotted classes to be
pickleable. If left None, it’s True by default for slotted classes
and False for dict classes.
If auto_detect is True, and getstate_setstate is left None, and
either__getstate__ or __setstate__ is detected
directly on the class (meaning: not inherited), it is set to False
(this is usually what you want).
auto_attribs (bool | None):
If True, look at type annotations to determine which attributes to
use, like dataclasses. If False, it will only look for explicit
field() class attributes, like classic attrs.
If left None, it will guess:
If any attributes are annotated and no unannotated
attrs.fields are found, it assumes auto_attribs=True.
Otherwise it assumes auto_attribs=False and tries to collect
attrs.fields.
If attrs decides to look at type annotations, all fields
must be annotated. If attrs encounters a field that is set to
a field() / attr.ib but lacks a type annotation, an
attrs.exceptions.UnannotatedAttributeError is raised. Use
field_name:typing.Any=field(...) if you don’t want to set a
type.
Warning
For features that use the attribute name to create decorators
(for example, validators), you still must
assign field() / attr.ib to them. Otherwise Python will
either not find the name or try to use the default value to
call, for example, validator on it.
Attributes annotated as typing.ClassVar, and attributes that are
neither annotated nor set to an field() are ignored.
these (dict[str, object]):
A dictionary of name to the (private) return value of field()
mappings. This is useful to avoid the definition of your attributes
within the class body because you can’t (for example, if you want
to add __repr__ methods to Django models) or don’t want to.
If these is not None, attrs will not search the class body
for attributes and will not remove any attributes from it.
The order is deduced from the order of the attributes inside
these.
Arguably, this is a rather obscure feature.
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).
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.
Note
The main differences to the classic attr.s are:
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
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.
Create a new instance, based on the first positional argument with
changes applied.
Args:
inst:
Instance of a class with attrs attributes. inst must be passed
as a positional argument.
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.
Changed in version 24.1.0: inst can’t be passed as a keyword argument anymore.
Callable that is called by attrs-generated __init__ methods
after the instance has been initialized. They receive the
initialized instance, the Attribute(), and the passed
value.
The return value is not inspected so the validator has to throw
an exception itself.
If a list is passed, its items are treated as validators and must
all pass.
Validators can be globally disabled and re-enabled using
attrs.validators.get_disabled / attrs.validators.set_disabled.
The validator can also be set using decorator notation as shown
below.
See also
validators
repr (bool | ~typing.Callable):
Include this attribute in the generated __repr__ method. If
True, include the attribute; if False, omit it. By default, the
built-in repr() function is used. To override how the 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,
which means it will be used directly instead of calling
repr() (the default).
eq (bool | ~typing.Callable):
If True (default), include this attribute in the generated
__eq__ and __ne__ methods that check two instances for
equality. To override how the attribute value is compared, pass a
callable that takes a single value and returns the value to be
compared.
See also
comparison
order (bool | ~typing.Callable):
If True (default), include this attributes in the generated
__lt__, __le__, __gt__ and __ge__ methods. To
override how the attribute value is ordered, pass a callable that
takes a single value and returns the value to be ordered.
See also
comparison
cmp(bool | ~typing.Callable):
Setting cmp is equivalent to setting eq and order to the same
value. Must not be mixed with eq or order.
See also
comparison
hash (bool | None):
Include this attribute in the generated __hash__ method. If
None (default), mirror eq’s value. This is the correct behavior
according the Python spec. Setting this value to anything else
than None is discouraged.
See also
hashing
init (bool):
Include this attribute in the generated __init__ method.
It is possible to set this to False and set a default value. In
that case this attributed is unconditionally initialized with the
specified default value or factory.
See also
init
converter (typing.Callable | Converter):
A callable that is called by attrs-generated __init__ methods
to convert attribute’s value to the desired format.
If a vanilla callable is passed, it is given the passed-in value as
the only positional argument. It is possible to receive additional
arguments by wrapping the callable in a Converter.
Either way, 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.
See also
converters
metadata (dict | None):
An arbitrary mapping, to be used by third-party code.
See also
extending-metadata.
type (type):
The type of the attribute. Nowadays, the preferred method to
specify the type is using a variable annotation (see PEP 526).
This argument is provided for backwards-compatibility and for usage
with make_class. Regardless of the approach used, the type will
be stored on Attribute.type.
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 static type
checking <types>.
kw_only (bool):
Make this attribute keyword-only in the generated __init__ (if
init is False, this parameter is ignored).
Allows to overwrite the on_setattr setting from attr.s. If left
None, the on_setattr value from attr.s is used. Set to
attrs.setters.NO_OP to run no setattr hooks for this
attribute – regardless of the setting in define().
alias (str | None):
Override this attribute’s parameter name in the generated
__init__ method. If left None, default to name stripped
of leading underscores. See private-attributes.
Added in version 20.1.0.
Changed in version 21.1.0: eq, order, and cmp also accept a custom callable
Added in version 22.2.0: alias
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.
A class decorator that adds dunder methods according to
fields specified using type annotations,
field() calls, or the these argument.
Since attrs patches or replaces an existing class, you cannot use
object.__init_subclass__ with attrs classes, because it runs too early.
As a replacement, you can define __attrs_init_subclass__ on your class.
It will be called by attrs classes that subclass it after they’re
created. See also init-subclass.
Args:
slots (bool):
Create a slotted class that’s more
memory-efficient. Slotted classes are generally superior to the
default dict classes, but have some gotchas you should know about,
so we encourage you to read the glossary entry.
auto_detect (bool):
Instead of setting the init, repr, eq, and hash arguments
explicitly, assume they are set to True unless any of the
involved methods for one of the arguments is implemented in the
current class (meaning, it is not inherited from some base
class).
So, for example by implementing __eq__ on a class yourself,
attrs will deduce eq=False and will create neither__eq__nor__ne__ (but Python classes come with a
sensible __ne__ by default, so it should be enough to only
implement __eq__ in most cases).
Passing True or False` to init, repr, eq, cmp, or hash
overrides whatever auto_detect would determine.
auto_exc (bool):
If the class subclasses BaseException (which implicitly includes
any subclass of any exception), the following happens to behave
like a well-behaved Python exception class:
the values for eq, order, and hash are ignored and the
instances compare and hash by the instance’s ids [2] ,
all attributes that are either passed into __init__ or have a
default value are additionally available as a tuple in the
args attribute,
the value of str is ignored leaving __str__ to base
classes.
A callable that is run whenever the user attempts to set an
attribute (either by assignment like i.x=42 or by using
setattr like setattr(i,"x",42)). It receives the same
arguments as validators: the instance, the attribute that is being
modified, and the new value.
If no exception is raised, the attribute is set to the return value
of the callable.
If a list of callables is passed, they’re automatically wrapped in
an attrs.setters.pipe.
If left None, the default behavior is to run converters and
validators whenever an attribute is set.
init (bool):
Create a __init__ method that initializes the attrs
attributes. Leading underscores are stripped for the argument name,
unless an alias is set on the attribute.
See also
init shows advanced ways to customize the generated
__init__ method, including executing code before and after.
repr(bool):
Create a __repr__ method with a human readable representation
of attrs attributes.
str (bool):
Create a __str__ method that is identical to __repr__. This
is usually not necessary except for Exceptions.
eq (bool | None):
If True or None (default), add __eq__ and __ne__ methods
that check two instances for equality.
See also
comparison describes how to customize the comparison behavior
going as far comparing NumPy arrays.
order (bool | None):
If True, add __lt__, __le__, __gt__, and __ge__
methods that behave like eq above and allow instances to be
ordered.
They compare the instances as if they were tuples of their attrs
attributes if and only if the types of both classes are
identical.
If None mirror value of eq.
See also
comparison
cmp (bool | None):
Setting cmp is equivalent to setting eq and order to the same
value. Must not be mixed with eq or order.
unsafe_hash (bool | None):
If None (default), the __hash__ method is generated according
how eq and frozen are set.
If both are True, attrs will generate a __hash__ for
you.
If eq is True and frozen is False, __hash__ will be set
to None, marking it unhashable (which it is).
If eq is False, __hash__ will be left untouched meaning
the __hash__ method of the base class will be used. If the
base class is object, this means it will fall back to id-based
hashing.
Although not recommended, you can decide for yourself and force
attrs to create one (for example, if the class is immutable even
though you didn’t freeze it programmatically) by passing True or
not. Both of these cases are rather special and should be used
carefully.
Deprecated alias for unsafe_hash. unsafe_hash takes precedence.
cache_hash (bool):
Ensure that the object’s hash code is computed only once and stored
on the object. If this is set to True, hashing must be either
explicitly or implicitly enabled for this class. If the hash code
is cached, avoid any reassignments of fields involved in hash code
computation or mutations of the objects those fields point to after
object creation. If such changes occur, the behavior of the
object’s hash code is undefined.
frozen (bool):
Make instances immutable after initialization. If someone attempts
to modify a frozen instance, attrs.exceptions.FrozenInstanceError
is raised.
Note
This is achieved by installing a custom __setattr__
method on your class, so you can’t implement your own.
True immutability is impossible in Python.
This does have a minor a runtime performance impact
<how-frozen> when initializing new instances. In other
words: __init__ is slightly slower with frozen=True.
If a class is frozen, you cannot modify self in
__attrs_post_init__ or a self-written __init__. You
can circumvent that limitation by using
object.__setattr__(self,"attribute_name",value).
Subclasses of a frozen class are frozen too.
kw_only (bool):
Make all attributes keyword-only in the generated __init__ (if
init is False, this parameter is ignored).
weakref_slot (bool):
Make instances weak-referenceable. This has no effect unless
slots is True.
field_transformer (~typing.Callable | None):
A function that is called with the original class object and all
fields right before attrs finalizes the class. You can use this,
for example, to automatically add converters or validators to
fields based on their types.
See also
transform-fields
match_args (bool):
If True (default), set __match_args__ on the class to support
PEP 634 (Structural Pattern Matching). It is a tuple of all
non-keyword-only __init__ parameter names on Python 3.10 and
later. Ignored on older Python versions.
collect_by_mro (bool):
If True, attrs collects attributes from base classes correctly
according to the method resolution order. If False, attrs
will mimic the (wrong) behavior of dataclasses and PEP 681.
This is usually only interesting for slotted classes and you
should probably just set auto_detect to True.
If True, __getstate__ and __setstate__ are generated and
attached to the class. This is necessary for slotted classes to be
pickleable. If left None, it’s True by default for slotted classes
and False for dict classes.
If auto_detect is True, and getstate_setstate is left None, and
either__getstate__ or __setstate__ is detected
directly on the class (meaning: not inherited), it is set to False
(this is usually what you want).
auto_attribs (bool | None):
If True, look at type annotations to determine which attributes to
use, like dataclasses. If False, it will only look for explicit
field() class attributes, like classic attrs.
If left None, it will guess:
If any attributes are annotated and no unannotated
attrs.fields are found, it assumes auto_attribs=True.
Otherwise it assumes auto_attribs=False and tries to collect
attrs.fields.
If attrs decides to look at type annotations, all fields
must be annotated. If attrs encounters a field that is set to
a field() / attr.ib but lacks a type annotation, an
attrs.exceptions.UnannotatedAttributeError is raised. Use
field_name:typing.Any=field(...) if you don’t want to set a
type.
Warning
For features that use the attribute name to create decorators
(for example, validators), you still must
assign field() / attr.ib to them. Otherwise Python will
either not find the name or try to use the default value to
call, for example, validator on it.
Attributes annotated as typing.ClassVar, and attributes that are
neither annotated nor set to an field() are ignored.
these (dict[str, object]):
A dictionary of name to the (private) return value of field()
mappings. This is useful to avoid the definition of your attributes
within the class body because you can’t (for example, if you want
to add __repr__ methods to Django models) or don’t want to.
If these is not None, attrs will not search the class body
for attributes and will not remove any attributes from it.
The order is deduced from the order of the attributes inside
these.
Arguably, this is a rather obscure feature.
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).
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.
Note
The main differences to the classic attr.s are:
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
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.
A class decorator that adds dunder methods according to
fields specified using type annotations,
field() calls, or the these argument.
Since attrs patches or replaces an existing class, you cannot use
object.__init_subclass__ with attrs classes, because it runs too early.
As a replacement, you can define __attrs_init_subclass__ on your class.
It will be called by attrs classes that subclass it after they’re
created. See also init-subclass.
Args:
slots (bool):
Create a slotted class that’s more
memory-efficient. Slotted classes are generally superior to the
default dict classes, but have some gotchas you should know about,
so we encourage you to read the glossary entry.
auto_detect (bool):
Instead of setting the init, repr, eq, and hash arguments
explicitly, assume they are set to True unless any of the
involved methods for one of the arguments is implemented in the
current class (meaning, it is not inherited from some base
class).
So, for example by implementing __eq__ on a class yourself,
attrs will deduce eq=False and will create neither__eq__nor__ne__ (but Python classes come with a
sensible __ne__ by default, so it should be enough to only
implement __eq__ in most cases).
Passing True or False` to init, repr, eq, cmp, or hash
overrides whatever auto_detect would determine.
auto_exc (bool):
If the class subclasses BaseException (which implicitly includes
any subclass of any exception), the following happens to behave
like a well-behaved Python exception class:
the values for eq, order, and hash are ignored and the
instances compare and hash by the instance’s ids [3] ,
all attributes that are either passed into __init__ or have a
default value are additionally available as a tuple in the
args attribute,
the value of str is ignored leaving __str__ to base
classes.
A callable that is run whenever the user attempts to set an
attribute (either by assignment like i.x=42 or by using
setattr like setattr(i,"x",42)). It receives the same
arguments as validators: the instance, the attribute that is being
modified, and the new value.
If no exception is raised, the attribute is set to the return value
of the callable.
If a list of callables is passed, they’re automatically wrapped in
an attrs.setters.pipe.
If left None, the default behavior is to run converters and
validators whenever an attribute is set.
init (bool):
Create a __init__ method that initializes the attrs
attributes. Leading underscores are stripped for the argument name,
unless an alias is set on the attribute.
See also
init shows advanced ways to customize the generated
__init__ method, including executing code before and after.
repr(bool):
Create a __repr__ method with a human readable representation
of attrs attributes.
str (bool):
Create a __str__ method that is identical to __repr__. This
is usually not necessary except for Exceptions.
eq (bool | None):
If True or None (default), add __eq__ and __ne__ methods
that check two instances for equality.
See also
comparison describes how to customize the comparison behavior
going as far comparing NumPy arrays.
order (bool | None):
If True, add __lt__, __le__, __gt__, and __ge__
methods that behave like eq above and allow instances to be
ordered.
They compare the instances as if they were tuples of their attrs
attributes if and only if the types of both classes are
identical.
If None mirror value of eq.
See also
comparison
cmp (bool | None):
Setting cmp is equivalent to setting eq and order to the same
value. Must not be mixed with eq or order.
unsafe_hash (bool | None):
If None (default), the __hash__ method is generated according
how eq and frozen are set.
If both are True, attrs will generate a __hash__ for
you.
If eq is True and frozen is False, __hash__ will be set
to None, marking it unhashable (which it is).
If eq is False, __hash__ will be left untouched meaning
the __hash__ method of the base class will be used. If the
base class is object, this means it will fall back to id-based
hashing.
Although not recommended, you can decide for yourself and force
attrs to create one (for example, if the class is immutable even
though you didn’t freeze it programmatically) by passing True or
not. Both of these cases are rather special and should be used
carefully.
Deprecated alias for unsafe_hash. unsafe_hash takes precedence.
cache_hash (bool):
Ensure that the object’s hash code is computed only once and stored
on the object. If this is set to True, hashing must be either
explicitly or implicitly enabled for this class. If the hash code
is cached, avoid any reassignments of fields involved in hash code
computation or mutations of the objects those fields point to after
object creation. If such changes occur, the behavior of the
object’s hash code is undefined.
frozen (bool):
Make instances immutable after initialization. If someone attempts
to modify a frozen instance, attrs.exceptions.FrozenInstanceError
is raised.
Note
This is achieved by installing a custom __setattr__
method on your class, so you can’t implement your own.
True immutability is impossible in Python.
This does have a minor a runtime performance impact
<how-frozen> when initializing new instances. In other
words: __init__ is slightly slower with frozen=True.
If a class is frozen, you cannot modify self in
__attrs_post_init__ or a self-written __init__. You
can circumvent that limitation by using
object.__setattr__(self,"attribute_name",value).
Subclasses of a frozen class are frozen too.
kw_only (bool):
Make all attributes keyword-only in the generated __init__ (if
init is False, this parameter is ignored).
weakref_slot (bool):
Make instances weak-referenceable. This has no effect unless
slots is True.
field_transformer (~typing.Callable | None):
A function that is called with the original class object and all
fields right before attrs finalizes the class. You can use this,
for example, to automatically add converters or validators to
fields based on their types.
See also
transform-fields
match_args (bool):
If True (default), set __match_args__ on the class to support
PEP 634 (Structural Pattern Matching). It is a tuple of all
non-keyword-only __init__ parameter names on Python 3.10 and
later. Ignored on older Python versions.
collect_by_mro (bool):
If True, attrs collects attributes from base classes correctly
according to the method resolution order. If False, attrs
will mimic the (wrong) behavior of dataclasses and PEP 681.
This is usually only interesting for slotted classes and you
should probably just set auto_detect to True.
If True, __getstate__ and __setstate__ are generated and
attached to the class. This is necessary for slotted classes to be
pickleable. If left None, it’s True by default for slotted classes
and False for dict classes.
If auto_detect is True, and getstate_setstate is left None, and
either__getstate__ or __setstate__ is detected
directly on the class (meaning: not inherited), it is set to False
(this is usually what you want).
auto_attribs (bool | None):
If True, look at type annotations to determine which attributes to
use, like dataclasses. If False, it will only look for explicit
field() class attributes, like classic attrs.
If left None, it will guess:
If any attributes are annotated and no unannotated
attrs.fields are found, it assumes auto_attribs=True.
Otherwise it assumes auto_attribs=False and tries to collect
attrs.fields.
If attrs decides to look at type annotations, all fields
must be annotated. If attrs encounters a field that is set to
a field() / attr.ib but lacks a type annotation, an
attrs.exceptions.UnannotatedAttributeError is raised. Use
field_name:typing.Any=field(...) if you don’t want to set a
type.
Warning
For features that use the attribute name to create decorators
(for example, validators), you still must
assign field() / attr.ib to them. Otherwise Python will
either not find the name or try to use the default value to
call, for example, validator on it.
Attributes annotated as typing.ClassVar, and attributes that are
neither annotated nor set to an field() are ignored.
these (dict[str, object]):
A dictionary of name to the (private) return value of field()
mappings. This is useful to avoid the definition of your attributes
within the class body because you can’t (for example, if you want
to add __repr__ methods to Django models) or don’t want to.
If these is not None, attrs will not search the class body
for attributes and will not remove any attributes from it.
The order is deduced from the order of the attributes inside
these.
Arguably, this is a rather obscure feature.
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).
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.
Note
The main differences to the classic attr.s are:
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
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.
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, for example, 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.
Args:
cls (type): Class to resolve.
globalns (dict | None): Dictionary containing global variables.
localns (dict | None): Dictionary containing local variables.
attribs (list | None):
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.