API Reference
attrs works by decorating a class using attrs.define
or attr.s
and then optionally defining attributes on the class using attrs.field
, attr.ib
, or a type annotation.
If you’re confused by the many names, please check out On The Core API Names for clarification.
What follows is the API explanation, if you’d like a more hands-on introduction, have a look at attrs by Example.
As of version 21.3.0, attrs consists of two top-level package names:
The classic
attr
that powered the venerableattr.s
andattr.ib
The modern
attrs
that only contains most modern APIs and relies onattrs.define
andattrs.field
to define your classes. Additionally it offers someattr
APIs with nicer defaults (e.g.attrs.asdict
).
The attrs
namespace is built on top of attr
which will never go away.
Core
Note
Please note that the attrs
namespace has been added in version 21.3.0.
Most of the objects are simply re-imported from attr
.
Therefore if a class, method, or function claims that it has been added in an older version, it is only available in the attr
namespace.
- attrs.NOTHING
Sentinel to indicate the lack of a value when
None
is ambiguous.If extending attrs, you can use
typing.Literal[NOTHING]
to show that a value may beNOTHING
.Changed in version 21.1.0:
bool(NOTHING)
is now False.Changed in version 22.2.0:
NOTHING
is now anenum.Enum
variant.
- attrs.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)
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).If frozen is
False
, run converters and validators when setting an attribute by default.slots=True
Caution
Usually this has only upsides and few visible effects in everyday programming. But it can lead to some suprising 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
orFalse
, it behaves exactly likeattr.s
. If leftNone
,attr.s
will try to guess:If any attributes are annotated and no unannotated
attrs.fields
s are found, it assumes auto_attribs=True.Otherwise it assumes auto_attribs=False and tries to collect
attrs.fields
s.
For now, please refer to
attr.s
for the rest of the parameters.New in version 20.1.0.
Changed in version 21.3.0: Converters are also run
on_setattr
.New in version 22.2.0: unsafe_hash as an alias for hash (for PEP 681 compliance).
- attrs.mutable(same_as_define)
Alias for
attrs.define
.New in version 20.1.0.
- attrs.frozen(same_as_define)
Behaves the same as
attrs.define
but sets frozen=True and on_setattr=None.New in version 20.1.0.
- attrs.field(*, default=_Nothing.NOTHING, validator=None, repr=True, hash=None, init=True, metadata=None, converter=None, factory=None, kw_only=False, eq=None, order=None, on_setattr=None, alias=None)
Identical to
attr.ib
, except keyword-only and with some arguments removed.New in version 20.1.0.
- attr.define()
Old import path for
attrs.define
.
- attr.mutable()
Old import path for
attrs.mutable
.
- attr.frozen()
Old import path for
attrs.frozen
.
- attr.field()
Old import path for
attrs.field
.
- class attrs.Attribute(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)
Read-only representation of an attribute.
The class has all arguments of
attr.ib
(except forfactory
which is only syntactic sugar fordefault=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
andorder_key
(typing.Callable
orNone
): The callables that are used for comparing and ordering objects by this attribute, respectively. These are set by passing a callable toattr.ib
’seq
,order
, orcmp
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.
New in version 20.1.0: inherited
New 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.
New in version 21.1.0: eq_key and order_key
New in version 22.2.0: alias
For the full version history of the fields, see
attr.ib
.For example:
>>> import attr >>> @attr.s ... class C: ... x = attr.ib() >>> attr.fields(C).x Attribute(name='x', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='x')
- evolve(**changes)
Copy self and apply changes.
This works similarly to
attr.evolve
but that function does not work withAttribute
.It is mainly meant to be used for Automatic Field Transformation and Modification.
New in version 20.3.0.
- attrs.make_class(name, attrs, bases=(<class 'object'>, ), **attributes_arguments)
A quick way to create a new class called name with attrs.
- Parameters
name (str) – The name for the new class.
A list of names or a dictionary of mappings of names to attributes.
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.
attributes_arguments – Passed unmodified to
attr.s
.
- Returns
A new class with attrs.
- Return type
New in version 17.1.0: bases
Changed in version 18.1.0: If attrs is ordered, the order is retained.
This is handy if you want to programmatically create classes.
For example:
>>> C1 = attr.make_class("C1", ["x", "y"]) >>> C1(1, 2) C1(x=1, y=2) >>> C2 = attr.make_class("C2", {"x": attr.ib(default=42), ... "y": attr.ib(default=attr.Factory(list))}) >>> C2() C2(x=42, y=[])
- class attrs.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.
New in version 17.1.0: takes_self
For example:
>>> @attr.s ... class C: ... x = attr.ib(default=attr.Factory(list)) ... y = attr.ib(default=attr.Factory( ... lambda self: set(self.x), ... takes_self=True) ... ) >>> C() C(x=[], y=set()) >>> C([1, 2, 3]) C(x=[1, 2, 3], y={1, 2, 3})
Classic
- attr.NOTHING
Same as
attrs.NOTHING
.
- 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.- Parameters
these (
dict
ofstr
toattr.ib
) –A dictionary of name to
attr.ib
mappings. This is 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 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.
repr_ns (str) – When using nested classes, there’s no way in Python 2 to automatically detect that. Therefore it’s possible to set the namespace explicitly for a more meaningful
repr
output.auto_detect (bool) –
Instead of setting the init, repr, eq, order, 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 (i.e. it is not inherited from some base class).So for example by implementing
__eq__
on a class yourself,attrs
will deduceeq=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).Warning
If you prevent
attrs
from creating the ordering methods for you (order=False
, e.g. by implementing__le__
), it becomes your responsibility to make sure its ordering is sound. The best way is to use thefunctools.total_ordering
decorator.Passing
True
orFalse
to init, repr, eq, order, cmp, or hash overrides whatever auto_detect would determine.repr (bool) – Create a
__repr__
method with a human readable representation ofattrs
attributes..str (bool) – Create a
__str__
method that is identical to__repr__
. This is usually not necessary except forException
s.eq (Optional[bool]) –
If
True
orNone
(default), add__eq__
and__ne__
methods that check two instances for equality.They compare the instances as if they were tuples of their
attrs
attributes if and only if the types of both classes are identical!order (Optional[bool]) – If
True
, add__lt__
,__le__
,__gt__
, and__ge__
methods that behave like eq above and allow instances to be ordered. IfNone
(default) mirror value of eq.cmp (Optional[bool]) – Setting cmp is equivalent to setting eq and order to the same value. Must not be mixed with eq or order.
unsafe_hash (Optional[bool]) –
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 base class isobject
, this means it will fall back to id-based hashing.).
Although not recommended, you can decide for yourself and force
attrs
to create one (e.g. if the class is immutable even though you didn’t freeze it programmatically) by passingTrue
or not. Both of these cases are rather special and should be used carefully.See our documentation on Hashing, Python’s documentation on
object.__hash__
, and the GitHub issue that led to the default behavior for more details.hash (Optional[bool]) – Alias for unsafe_hash. unsafe_hash takes precedence.
init (bool) –
Create a
__init__
method that initializes theattrs
attributes. Leading underscores are stripped for the argument name. If a__attrs_pre_init__
method exists on the class, it will be called before the class is initialized. If a__attrs_post_init__
method exists on the class, it will be called after the class is fully initialized.If
init
isFalse
, an__attrs_init__
method will be injected instead. This allows you to define a custom__init__
method that can do pre-init work such assuper().__init__()
, and then call__attrs_init__()
and__attrs_post_init__()
.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.
frozen (bool) –
Make instances immutable after initialization. If someone attempts to modify a frozen instance,
attr.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 when initializing new instances. In other words:
__init__
is slightly slower withfrozen=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 usingobject.__setattr__(self, "attribute_name", value)
.Subclasses of a frozen class are frozen too.
weakref_slot (bool) – Make instances weak-referenceable. This has no effect unless
slots
is also enabled.auto_attribs (bool) –
If
True
, collect PEP 526-annotated attributes from the class body.In this case, you must annotate every field. If
attrs
encounters a field that is set to anattr.ib
but lacks a type annotation, anattr.exceptions.UnannotatedAttributeError
is raised. Usefield_name: typing.Any = attr.ib(...)
if you don’t want to set a type.If you assign a value to those attributes (e.g.
x: int = 42
), that value becomes the default value like if it were passed usingattr.ib(default=42)
. Passing an instance ofattrs.Factory
also works as expected in most cases (see warning below).Attributes annotated as
typing.ClassVar
, and attributes that are neither annotated nor set to anattr.ib
are ignored.Warning
For features that use the attribute name to create decorators (e.g. validators), you still must assign
attr.ib
to them. Otherwise Python will either not find the name or try to use the default value to call e.g.validator
on it.These errors can be quite confusing and probably the most common bug report on our bug tracker.
kw_only (bool) – Make all attributes keyword-only in the generated
__init__
(ifinit
isFalse
, this parameter is ignored).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.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 exceptions class:the values for eq, order, and hash are ignored and the instances compare and hash by the instance’s ids (N.B.
attrs
will not remove existing implementations of__hash__
or the equality methods. It just won’t add own ones.),all attributes that are either passed into
__init__
or have a default value are additionally available as a tuple in theargs
attribute,the value of str is ignored leaving
__str__
to base classes.
collect_by_mro (bool) –
Setting this to
True
fixes the wayattrs
collects attributes from base classes. The default behavior is incorrect in certain cases of multiple inheritance. It should be on by default but is kept off for backward-compatibility.See issue #428 for more details.
getstate_setstate (Optional[bool]) –
Note
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 leftNone
, it’sTrue
by default for slotted classes andFalse
for dict classes.If auto_detect is
True
, and getstate_setstate is leftNone
, and either__getstate__
or__setstate__
is detected directly on the class (i.e. not inherited), it is set toFalse
(this is usually what you want).on_setattr (
callable
, or a list of callables, orNone
, orattrs.setters.NO_OP
) –A callable that is run whenever the user attempts to set an attribute (either by assignment like
i.x = 42
or by usingsetattr
likesetattr(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
.field_transformer (Optional[callable]) – A function that is called with the original class object and all fields right before
attrs
finalizes the class. You can use this, e.g., to automatically add converters or validators to fields based on their types. See Automatic Field Transformation and Modification for more details.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.
New in version 16.0.0: slots
New in version 16.1.0: frozen
New in version 16.3.0: str
New 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.New 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.
New in version 18.2.0: weakref_slot
Deprecated since version 18.2.0:
__lt__
,__le__
,__gt__
, and__ge__
now raise aDeprecationWarning
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.New in version 18.2.0: kw_only
New in version 18.2.0: cache_hash
New in version 19.1.0: auto_exc
Deprecated since version 19.2.0: cmp Removal on or after 2021-06-01.
New in version 19.2.0: eq and order
New in version 20.1.0: auto_detect
New in version 20.1.0: collect_by_mro
New in version 20.1.0: getstate_setstate
New in version 20.1.0: on_setattr
New 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
New in version 21.3.0: match_args
New in version 22.2.0: unsafe_hash as an alias for hash (for PEP 681 compliance).
Note
attrs also comes with a serious-business alias
attr.attrs
.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.NOTHING, validator=None, repr=True, cmp=None, hash=None, init=True, metadata=None, type=None, converter=None, factory=None, kw_only=False, eq=None, order=None, on_setattr=None, alias=None)
Create a new attribute on a class.
Warning
Does not do anything unless the class is also decorated with
attr.s
!- Parameters
default (Any value) –
A value that is used if an
attrs
-generated__init__
is used and no value is passed while instantiating or the attribute is excluded usinginit=False
.If the value is an instance of
attrs.Factory
, its callable will be used to construct a new value (useful for mutable data types like lists or dicts).If a default is not set (or set manually to
attrs.NOTHING
), a value must be supplied when instantiating; otherwise aTypeError
will be raised.The default can also be set using decorator notation as shown below.
factory (callable) – Syntactic sugar for
default=attr.Factory(factory)
.validator (
callable
or alist
ofcallable
s.) –callable
that is called byattrs
-generated__init__
methods after the instance has been initialized. They receive the initialized instance, theAttribute()
, 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
get_run_validators
.The validator can also be set using decorator notation as shown below.
repr (a
bool
or acallable
to use a custom function.) – Include this attribute in the generated__repr__
method. IfTrue
, include the attribute; ifFalse
, omit it. By default, the built-inrepr()
function is used. To override how the attribute value is formatted, pass acallable
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 callingrepr()
(the default).eq (a
bool
or acallable
.) – IfTrue
(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 acallable
that takes a single value and returns the value to be compared.order (a
bool
or acallable
.) – IfTrue
(default), include this attributes in the generated__lt__
,__le__
,__gt__
and__ge__
methods. To override how the attribute value is ordered, pass acallable
that takes a single value and returns the value to be ordered.cmp (a
bool
or acallable
.) – Setting cmp is equivalent to setting eq and order to the same value. Must not be mixed with eq or order.hash (Optional[bool]) – Include this attribute in the generated
__hash__
method. IfNone
(default), mirror eq’s value. This is the correct behavior according the Python spec. Setting this value to anything else thanNone
is discouraged.init (bool) – Include this attribute in the generated
__init__
method. It is possible to set this toFalse
and set a default value. In that case this attributed is unconditionally initialized with the specified default value or factory.converter (callable) –
callable
that is called byattrs
-generated__init__
methods to convert attribute’s value 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 value is converted before being passed to the validator, if any.metadata – An arbitrary mapping, to be used by third-party components. See Metadata.
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 backward compatibility. 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.kw_only – Make this attribute keyword-only in the generated
__init__
(ifinit
isFalse
, this parameter is ignored).on_setattr (
callable
, or a list of callables, orNone
, orattrs.setters.NO_OP
) – Allows to overwrite the on_setattr setting fromattr.s
. If leftNone
, the on_setattr value fromattr.s
is used. Set toattrs.setters.NO_OP
to run nosetattr
hooks for this attribute – regardless of the setting inattr.s
.alias (Optional[str]) – Override this attribute’s parameter name in the generated
__init__
method. If leftNone
, default toname
stripped of leading underscores. See Private Attributes and Aliases.
New in version 15.2.0: convert
New 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.New in version 17.3.0: type
Deprecated since version 17.4.0: convert
New in version 17.4.0: converter as a replacement for the deprecated convert to achieve consistency with other noun-based arguments.
New in version 18.1.0:
factory=f
is syntactic sugar fordefault=attr.Factory(f)
.New 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.
New in version 19.2.0: eq and order
New 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
New in version 22.2.0: alias
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
Exceptions
All exceptions are available from both attr.exceptions
and attrs.exceptions
and are the same thing.
That means that it doesn’t matter from from which namespace they’ve been raised and/or caught:
>>> import attrs, attr
>>> try:
... raise attrs.exceptions.FrozenError()
... except attr.exceptions.FrozenError:
... print("this works!")
this works!
- exception attrs.exceptions.PythonTooOldError
It was attempted to use an
attrs
feature that requires a newer Python version.New in version 18.2.0.
- exception attrs.exceptions.FrozenError
A frozen/immutable instance or attribute have been attempted to be modified.
It mirrors the behavior of
namedtuples
by using the same error message and subclassingAttributeError
.New in version 20.1.0.
- exception attrs.exceptions.FrozenInstanceError
A frozen instance has been attempted to be modified.
New in version 16.1.0.
- exception attrs.exceptions.FrozenAttributeError
A frozen attribute has been attempted to be modified.
New in version 20.1.0.
- exception attrs.exceptions.AttrsAttributeNotFoundError
An
attrs
function couldn’t find an attribute that the user asked for.New in version 16.2.0.
- exception attrs.exceptions.NotAnAttrsClassError
A non-
attrs
class has been passed into anattrs
function.New in version 16.2.0.
- exception attrs.exceptions.DefaultAlreadySetError
A default has been set using
attr.ib()
and is attempted to be reset using the decorator.New in version 17.1.0.
- exception attrs.exceptions.UnannotatedAttributeError
A class with
auto_attribs=True
has anattr.ib()
without a type annotation.New in version 17.3.0.
- exception attrs.exceptions.NotCallableError(msg, value)
A
attr.ib()
requiring a callable has been set with a value that is not callable.New in version 19.2.0.
For example:
@attr.s(auto_attribs=True) class C: x: int y = attr.ib() # <- ERROR!
Helpers
attrs comes with a bunch of helper methods that make working with it easier:
- attrs.cmp_using(eq=None, lt=None, le=None, gt=None, ge=None, require_same_type=True, class_name='Comparable')
Create a class that can be passed into
attr.ib
’seq
,order
, andcmp
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}
andeq
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 returnNotImplemented
if objects are not of the same type.class_name (Optional[str]) – Name of class. Defaults to ‘Comparable’.
See Comparison for more details.
New in version 21.1.0.
- attr.cmp_using()
Same as
attrs.cmp_using
.
- attrs.fields(cls)
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.
attr.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.
For example:
>>> @attr.s ... class C: ... x = attr.ib() ... y = attr.ib() >>> attrs.fields(C) (Attribute(name='x', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='x'), Attribute(name='y', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='y')) >>> attrs.fields(C)[1] Attribute(name='y', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='y') >>> attrs.fields(C).y is attrs.fields(C)[1] True
- attr.fields()
Same as
attrs.fields
.
- attrs.fields_dict(cls)
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.
attr.exceptions.NotAnAttrsClassError – If cls is not an
attrs
class.
- Return type
New in version 18.1.0.
For example:
>>> @attr.s ... class C: ... x = attr.ib() ... y = attr.ib() >>> attrs.fields_dict(C) {'x': Attribute(name='x', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='x'), 'y': Attribute(name='y', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='y')} >>> attr.fields_dict(C)['y'] Attribute(name='y', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='y') >>> attrs.fields_dict(C)['y'] is attrs.fields(C).y True
- attr.fields_dict()
Same as
attrs.fields_dict
.
- attrs.has(cls)
Check whether cls is a class with
attrs
attributes.For example:
>>> @attr.s ... class C: ... pass >>> attr.has(C) True >>> attr.has(object) False
- attrs.resolve_types(cls, globalns=None, localns=None, attribs=None)
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 anattrs
class yet.
- Raises
TypeError – If cls is not a class.
attr.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 beforeattrs.define
.
New in version 20.1.0.
New in version 21.1.0: attribs
For example:
>>> import typing >>> @attrs.define ... class A: ... a: typing.List['A'] ... b: 'B' ... >>> @attrs.define ... class B: ... a: A ... >>> attrs.fields(A).a.type typing.List[ForwardRef('A')] >>> attrs.fields(A).b.type 'B' >>> attrs.resolve_types(A, globals(), locals()) <class 'A'> >>> attrs.fields(A).a.type typing.List[A] >>> attrs.fields(A).b.type <class 'B'>
- attr.resolve_types()
Same as
attrs.resolve_types
.
- attrs.asdict(inst, *, recurse=True, filter=None, value_serializer=None)
Same as
attr.asdict
, except that collections types are always retained and dict is always used as dict_factory.New in version 21.3.0.
For example:
>>> @attrs.define ... class C: ... x: int ... y: int >>> attrs.asdict(C(1, C(2, 3))) {'x': 1, 'y': {'x': 2, 'y': 3}}
- 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 theattrs.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 istuple
orset
. Only meaningful ifrecurse
isTrue
.value_serializer (Optional[callable]) – 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.
- Return type
return type of dict_factory
- Raises
attr.exceptions.NotAnAttrsClassError – If cls is not an
attrs
class.
New in version 16.0.0: dict_factory
New in version 16.1.0: retain_collection_types
New in version 20.3.0: value_serializer
New in version 21.3.0: If a dict has a collection for a key, it is serialized as a tuple.
- attrs.astuple(inst, *, recurse=True, filter=None)
Same as
attr.astuple
, except that collections types are always retained andtuple
is always used as the tuple_factory.New in version 21.3.0.
For example:
>>> @attrs.define ... class C: ... x = attr.field() ... y = attr.field() >>> attrs.astuple(C(1,2)) (1, 2)
- 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 theattrs.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
ordict
when encountering an attribute which type istuple
,dict
orset
. Only meaningful ifrecurse
isTrue
.
- Return type
return type of tuple_factory
- Raises
attr.exceptions.NotAnAttrsClassError – If cls is not an
attrs
class.
New in version 16.2.0.
attrs includes some handy helpers for filtering the attributes in attrs.asdict
and attrs.astuple
:
- attrs.filters.include(*what)
Include what.
- Parameters
what (
list
oftype
orattrs.Attribute
s) – What to include.- Return type
- attrs.filters.exclude(*what)
Exclude what.
- Parameters
what (
list
of classes orattrs.Attribute
s.) – What to exclude.- Return type
- 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 from attr.filters
.
- attrs.evolve(inst, **changes)
Create a new instance, based on inst 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__
.attr.exceptions.NotAnAttrsClassError – If cls is not an
attrs
class.
New in version 17.1.0.
For example:
>>> @attrs.define ... class C: ... x: int ... y: int >>> i1 = C(1, 2) >>> i1 C(x=1, y=2) >>> i2 = attrs.evolve(i1, y=3) >>> i2 C(x=1, y=3) >>> i1 == i2 False
evolve
creates a new instance using__init__
. This fact has several implications:private attributes should be specified without the leading underscore, just like in
__init__
.attributes with
init=False
can’t be set withevolve
.the usual
__init__
validators will validate the new values.
- attr.evolve()
Same as
attrs.evolve
.
- attrs.validate(inst)
Validate all attributes on inst that have a validator.
Leaves all exceptions through.
- Parameters
inst – Instance of a class with
attrs
attributes.
For example:
>>> @attrs.define(on_setattr=attrs.setters.NO_OP) ... class C: ... x = attrs.field(validator=attrs.validators.instance_of(int)) >>> i = C(1) >>> i.x = "1" >>> attrs.validate(i) Traceback (most recent call last): ... TypeError: ("'x' must be <class 'int'> (got '1' that is a <class 'str'>).", ...)
- attr.validate()
Same as
attrs.validate
.
Validators can be globally disabled if you want to run them only in development and tests but not in production because you fear their performance impact:
- 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. Useattrs.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. Useattrs.validators.get_disabled()
instead.
Validators
attrs comes with some common validators in the attrs.validators
module.
All objects from attrs.validators
are also available from attr.validators
.
- attrs.validators.lt(val)
A validator that raises
ValueError
if the initializer is called with a number larger or equal to val.- Parameters
val – Exclusive upper bound for values
New in version 21.3.0.
For example:
>>> @attrs.define ... class C: ... x = attrs.field(validator=attrs.validators.lt(42)) >>> C(41) C(x=41) >>> C(42) Traceback (most recent call last): ... ValueError: ("'x' must be < 42: 42")
- attrs.validators.le(val)
A validator that raises
ValueError
if the initializer is called with a number greater than val.- Parameters
val – Inclusive upper bound for values
New in version 21.3.0.
For example:
>>> @attrs.define ... class C: ... x = attrs.field(validator=attr.validators.le(42)) >>> C(42) C(x=42) >>> C(43) Traceback (most recent call last): ... ValueError: ("'x' must be <= 42: 43")
- attrs.validators.ge(val)
A validator that raises
ValueError
if the initializer is called with a number smaller than val.- Parameters
val – Inclusive lower bound for values
New in version 21.3.0.
For example:
>>> @attrs.define ... class C: ... x = attrs.field(validator=attrs.validators.ge(42)) >>> C(42) C(x=42) >>> C(41) Traceback (most recent call last): ... ValueError: ("'x' must be => 42: 41")
- attrs.validators.gt(val)
A validator that raises
ValueError
if the initializer is called with a number smaller or equal to val.- Parameters
val – Exclusive lower bound for values
New in version 21.3.0.
For example:
>>> @attrs.define ... class C: ... x = attr.field(validator=attrs.validators.gt(42)) >>> C(43) C(x=43) >>> C(42) Traceback (most recent call last): ... ValueError: ("'x' must be > 42: 42")
- attrs.validators.max_len(length)
A validator that raises
ValueError
if the initializer is called with a string or iterable that is longer than length.- Parameters
length (int) – Maximum length of the string or iterable
New in version 21.3.0.
For example:
>>> @attrs.define ... class C: ... x = attrs.field(validator=attrs.validators.max_len(4)) >>> C("spam") C(x='spam') >>> C("bacon") Traceback (most recent call last): ... ValueError: ("Length of 'x' must be <= 4: 5")
- attrs.validators.min_len(length)
A validator that raises
ValueError
if the initializer is called with a string or iterable that is shorter than length.- Parameters
length (int) – Minimum length of the string or iterable
New in version 22.1.0.
For example:
>>> @attrs.define ... class C: ... x = attrs.field(validator=attrs.validators.min_len(1)) >>> C("bacon") C(x='bacon') >>> C("") Traceback (most recent call last): ... ValueError: ("Length of 'x' must be => 1: 0")
- attrs.validators.instance_of(type)
A validator that raises a
TypeError
if the initializer is called with a wrong type for this particular attribute (checks are performed usingisinstance
therefore it’s also valid to pass a tuple of types).- Parameters
- Raises
TypeError – With a human readable error message, the attribute (of type
attrs.Attribute
), the expected type, and the value it got.
For example:
>>> @attrs.define ... class C: ... x = attrs.field(validator=attrs.validators.instance_of(int)) >>> C(42) C(x=42) >>> C("42") Traceback (most recent call last): ... TypeError: ("'x' must be <type 'int'> (got '42' that is a <type 'str'>).", Attribute(name='x', default=NOTHING, validator=<instance_of validator for type <type 'int'>>, type=None, kw_only=False), <type 'int'>, '42') >>> C(None) Traceback (most recent call last): ... TypeError: ("'x' must be <type 'int'> (got None that is a <type 'NoneType'>).", Attribute(name='x', default=NOTHING, validator=<instance_of validator for type <type 'int'>>, repr=True, cmp=True, hash=None, init=True, type=None, kw_only=False), <type 'int'>, None)
- attrs.validators.in_(options)
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 performed usingvalue in options
.- Parameters
options (list, tuple,
enum.Enum
, …) – Allowed options.- Raises
ValueError – With a human readable error message, the attribute (of type
attrs.Attribute
), the expected options, and the value it got.
New in version 17.1.0.
Changed in version 22.1.0: The ValueError was incomplete until now and only contained the human readable error message. Now it contains all the information that has been promised since 17.1.0.
For example:
>>> import enum >>> class State(enum.Enum): ... ON = "on" ... OFF = "off" >>> @attrs.define ... class C: ... state = attrs.field(validator=attrs.validators.in_(State)) ... val = attrs.field(validator=attrs.validators.in_([1, 2, 3])) >>> C(State.ON, 1) C(state=<State.ON: 'on'>, val=1) >>> C("on", 1) Traceback (most recent call last): ... ValueError: 'state' must be in <enum 'State'> (got 'on'), Attribute(name='state', default=NOTHING, validator=<in_ validator with options <enum 'State'>>, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None), <enum 'State'>, 'on') >>> C(State.ON, 4) Traceback (most recent call last): ... ValueError: 'val' must be in [1, 2, 3] (got 4), Attribute(name='val', default=NOTHING, validator=<in_ validator with options [1, 2, 3]>, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False, inherited=False, on_setattr=None), [1, 2, 3], 4)
- attrs.validators.provides(interface)
A validator that raises a
TypeError
if the initializer is called with an object that does not provide the requested interface (checks are performed usinginterface.providedBy(value)
(see zope.interface).- Parameters
interface (
zope.interface.Interface
) – The interface to check for.- Raises
TypeError – With a human readable error message, the attribute (of type
attrs.Attribute
), the expected interface, and the value it got.
- attrs.validators.and_(*validators)
A validator that composes multiple validators into one.
When called on a value, it runs all wrapped validators.
- Parameters
validators (callables) – Arbitrary number of validators.
New in version 17.1.0.
For convenience, it’s also possible to pass a list to
attrs.field
’s validator argument.Thus the following two statements are equivalent:
x = attrs.field(validator=attrs.validators.and_(v1, v2, v3)) x = attrs.field(validator=[v1, v2, v3])
- attrs.validators.not_(validator, *, msg=None, exc_types=(<class 'ValueError'>, <class 'TypeError'>))
A validator that wraps and logically ‘inverts’ the validator passed to it. It will raise a
ValueError
if the provided validator doesn’t raise aValueError
orTypeError
(by default), and will suppress the exception if the provided validator does.Intended to be used with existing validators to compose logic without needing to create inverted variants, for example,
not_(in_(...))
.- Parameters
validator – A validator to be logically inverted.
msg (str) – Message to raise if validator fails. Formatted with keys
exc_types
andvalidator
.exc_types – Exception type(s) to capture. Other types raised by child validators will not be intercepted and pass through.
- Raises
ValueError – With a human readable error message, the attribute (of type
attrs.Attribute
), the validator that failed to raise an exception, the value it got, and the expected exception types.
New in version 22.2.0.
For example:
>>> reserved_names = {"id", "time", "source"} >>> @attrs.define ... class Measurement: ... tags = attrs.field( ... validator=attrs.validators.deep_mapping( ... key_validator=attrs.validators.not_( ... attrs.validators.in_(reserved_names), ... msg="reserved tag key", ... ), ... value_validator=attrs.validators.instance_of((str, int)), ... ) ... ) >>> Measurement(tags={"source": "universe"}) Traceback (most recent call last): ... ValueError: ("reserved tag key", Attribute(name='tags', default=NOTHING, validator=<not_ validator wrapping <in_ validator with options {'id', 'time', 'source'}>, capturing (<class 'ValueError'>, <class 'TypeError'>)>, type=None, kw_only=False), <in_ validator with options {'id', 'time', 'source'}>, {'source_': 'universe'}, (<class 'ValueError'>, <class 'TypeError'>)) >>> Measurement(tags={"source_": "universe"}) Measurement(tags={'source_': 'universe'})
- attrs.validators.optional(validator)
A validator that makes an attribute optional. An optional attribute is one which can be set to
None
in addition to satisfying the requirements of the sub-validator.- Parameters
validator (callable or
list
of callables.) – A validator (or a list of validators) that is used for non-None
values.
New in version 15.1.0.
Changed in version 17.1.0: validator can be a list of validators.
For example:
>>> @attrs.define ... class C: ... x = attrs.field(validator=attrs.validators.optional(attr.validators.instance_of(int))) >>> C(42) C(x=42) >>> C("42") Traceback (most recent call last): ... TypeError: ("'x' must be <type 'int'> (got '42' that is a <type 'str'>).", Attribute(name='x', default=NOTHING, validator=<instance_of validator for type <type 'int'>>, type=None, kw_only=False), <type 'int'>, '42') >>> C(None) C(x=None)
- attrs.validators.is_callable()
A validator that raises a
attr.exceptions.NotCallableError
if the initializer is called with a value for this particular attribute that is not callable.New in version 19.1.0.
- Raises
attr.exceptions.NotCallableError – With a human readable error message containing the attribute (
attrs.Attribute
) name, and the value it got.
For example:
>>> @attrs.define ... class C: ... x = attrs.field(validator=attrs.validators.is_callable()) >>> C(isinstance) C(x=<built-in function isinstance>) >>> C("not a callable") Traceback (most recent call last): ... attr.exceptions.NotCallableError: 'x' must be callable (got 'not a callable' that is a <class 'str'>).
- attrs.validators.matches_re(regex, flags=0, func=None)
A validator that raises
ValueError
if the initializer is called with a string that doesn’t match regex.- Parameters
regex – a regex string or precompiled pattern to match against
flags (int) – flags that will be passed to the underlying re function (default 0)
func (callable) – which underlying
re
function to call. Valid options arere.fullmatch
,re.search
, andre.match
; the defaultNone
meansre.fullmatch
. For performance reasons, the pattern is always precompiled usingre.compile
.
New in version 19.2.0.
Changed in version 21.3.0: regex can be a pre-compiled pattern.
For example:
>>> @attrs.define ... class User: ... email = attrs.field(validator=attrs.validators.matches_re( ... "(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")) >>> User(email="user@example.com") User(email='user@example.com') >>> User(email="user@example.com@test.com") Traceback (most recent call last): ... ValueError: ("'email' must match regex '(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\\\.[a-zA-Z0-9-.]+$)' ('user@example.com@test.com' doesn't)", Attribute(name='email', default=NOTHING, validator=<matches_re validator for pattern re.compile('(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)')>, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), re.compile('(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)'), 'user@example.com@test.com')
- attrs.validators.deep_iterable(member_validator, iterable_validator=None)
A validator that performs deep validation of an iterable.
- Parameters
member_validator – Validator(s) to apply to iterable members
iterable_validator – Validator to apply to iterable itself (optional)
New in version 19.1.0.
- Raises
TypeError – if any sub-validators fail
For example:
>>> @attrs.define ... class C: ... x = attrs.field(validator=attrs.validators.deep_iterable( ... member_validator=attrs.validators.instance_of(int), ... iterable_validator=attrs.validators.instance_of(list) ... )) >>> C(x=[1, 2, 3]) C(x=[1, 2, 3]) >>> C(x=set([1, 2, 3])) Traceback (most recent call last): ... TypeError: ("'x' must be <class 'list'> (got {1, 2, 3} that is a <class 'set'>).", Attribute(name='x', default=NOTHING, validator=<deep_iterable validator for <instance_of validator for type <class 'list'>> iterables of <instance_of validator for type <class 'int'>>>, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), <class 'list'>, {1, 2, 3}) >>> C(x=[1, 2, "3"]) Traceback (most recent call last): ... TypeError: ("'x' must be <class 'int'> (got '3' that is a <class 'str'>).", Attribute(name='x', default=NOTHING, validator=<deep_iterable validator for <instance_of validator for type <class 'list'>> iterables of <instance_of validator for type <class 'int'>>>, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), <class 'int'>, '3')
- attrs.validators.deep_mapping(key_validator, value_validator, mapping_validator=None)
A validator that performs deep validation of a dictionary.
- Parameters
key_validator – Validator to apply to dictionary keys
value_validator – Validator to apply to dictionary values
mapping_validator – Validator to apply to top-level mapping attribute (optional)
New in version 19.1.0.
- Raises
TypeError – if any sub-validators fail
For example:
>>> @attrs.define ... class C: ... x = attrs.field(validator=attrs.validators.deep_mapping( ... key_validator=attrs.validators.instance_of(str), ... value_validator=attrs.validators.instance_of(int), ... mapping_validator=attrs.validators.instance_of(dict) ... )) >>> C(x={"a": 1, "b": 2}) C(x={'a': 1, 'b': 2}) >>> C(x=None) Traceback (most recent call last): ... TypeError: ("'x' must be <class 'dict'> (got None that is a <class 'NoneType'>).", Attribute(name='x', default=NOTHING, validator=<deep_mapping validator for objects mapping <instance_of validator for type <class 'str'>> to <instance_of validator for type <class 'int'>>>, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), <class 'dict'>, None) >>> C(x={"a": 1.0, "b": 2}) Traceback (most recent call last): ... TypeError: ("'x' must be <class 'int'> (got 1.0 that is a <class 'float'>).", Attribute(name='x', default=NOTHING, validator=<deep_mapping validator for objects mapping <instance_of validator for type <class 'str'>> to <instance_of validator for type <class 'int'>>>, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), <class 'int'>, 1.0) >>> C(x={"a": 1, 7: 2}) Traceback (most recent call last): ... TypeError: ("'x' must be <class 'str'> (got 7 that is a <class 'int'>).", Attribute(name='x', default=NOTHING, validator=<deep_mapping validator for objects mapping <instance_of validator for type <class 'str'>> to <instance_of validator for type <class 'int'>>>, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), <class 'str'>, 7)
Validators can be both globally and locally disabled:
- attrs.validators.set_disabled(disabled)
Globally disable or enable running validators.
By default, they are run.
- Parameters
disabled (bool) – If
True
, disable running all validators.
Warning
This function is not thread-safe!
New in version 21.3.0.
- attrs.validators.get_disabled()
Return a bool indicating whether validators are currently disabled or not.
- Returns
True
if validators are currently disabled.- Return type
New in version 21.3.0.
- attrs.validators.disabled()
Context manager that disables running validators within its context.
Warning
This context manager is not thread-safe!
New in version 21.3.0.
Converters
All objects from attrs.converters
are also available from attr.converters
.
- attrs.converters.pipe(*converters)
A converter that composes multiple converters into one.
When called on a value, it runs all wrapped converters, returning the last value.
Type annotations will be inferred from the wrapped converters’, if they have any.
- Parameters
converters (callables) – Arbitrary number of converters.
New in version 20.1.0.
For convenience, it’s also possible to pass a list to
attr.ib
’s converter argument.Thus the following two statements are equivalent:
x = attr.ib(converter=attr.converter.pipe(c1, c2, c3)) x = attr.ib(converter=[c1, c2, c3])
- attrs.converters.optional(converter)
A converter that allows an attribute to be optional. An optional attribute is one which can be set to
None
.Type annotations will be inferred from the wrapped converter’s, if it has any.
- Parameters
converter (callable) – the converter that is used for non-
None
values.
New in version 17.1.0.
For example:
>>> @attr.s ... class C: ... x = attr.ib(converter=attr.converters.optional(int)) >>> C(None) C(x=None) >>> C(42) C(x=42)
- attrs.converters.default_if_none(default=_Nothing.NOTHING, factory=None)
A converter that allows to replace
None
values by default or the result of factory.- Parameters
default – Value to be used if
None
is passed. Passing an instance ofattrs.Factory
is supported, however thetakes_self
option is not.factory (callable) – A callable that takes no parameters whose result is used if
None
is passed.
- Raises
TypeError – If neither default or factory is passed.
TypeError – If both default and factory are passed.
ValueError – If an instance of
attrs.Factory
is passed withtakes_self=True
.
New in version 18.2.0.
For example:
>>> @attr.s ... class C: ... x = attr.ib( ... converter=attr.converters.default_if_none("") ... ) >>> C(None) C(x='')
- attrs.converters.to_bool(val)
Convert “boolean” strings (e.g., from env. vars.) to real booleans.
Values mapping to
True
:True
"true"
/"t"
"yes"
/"y"
"on"
"1"
1
Values mapping to
False
:False
"false"
/"f"
"no"
/"n"
"off"
"0"
0
- Raises
ValueError – for any other value.
New in version 21.3.0.
For example:
>>> @attr.s ... class C: ... x = attr.ib( ... converter=attr.converters.to_bool ... ) >>> C("yes") C(x=True) >>> C(0) C(x=False) >>> C("foo") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Cannot convert value to bool: foo
Setters
These are helpers that you can use together with attrs.define
’s and attrs.fields
’s on_setattr
arguments.
All setters in attrs.setters
are also available from attr.setters
.
- attrs.setters.frozen(_, __, ___)
Prevent an attribute to be modified.
New in version 20.1.0.
- attrs.setters.validate(instance, attrib, new_value)
Run attrib’s validator on new_value if it has one.
New in version 20.1.0.
- attrs.setters.convert(instance, attrib, new_value)
Run attrib’s converter – if it has one – on new_value and return the result.
New in version 20.1.0.
- attrs.setters.pipe(*setters)
Run all setters and return the return value of the last one.
New in version 20.1.0.
- attrs.setters.NO_OP
Sentinel for disabling class-wide on_setattr hooks for certain attributes.
Does not work in
attrs.setters.pipe
or within lists.New in version 20.1.0.
For example, only
x
is frozen here:>>> @attrs.define(on_setattr=attr.setters.frozen) ... class C: ... x = attr.field() ... y = attr.field(on_setattr=attr.setters.NO_OP) >>> c = C(1, 2) >>> c.y = 3 >>> c.y 3 >>> c.x = 4 Traceback (most recent call last): ... attrs.exceptions.FrozenAttributeError: ()
N.B. Please use
attrs.define
’s frozen argument (orattrs.frozen
) to freeze whole classes; it is more efficient.
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 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
New 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
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.
- attr.assoc(inst, **changes)
Copy inst and apply changes.
- 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
attr.exceptions.AttrsAttributeNotFoundError – If attr_name couldn’t be found on cls.
attr.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 toattrs.evolve
.