API¶
attrs works by decorating a class using attr.s() and then optionally defining attributes on the class using attr.ib().
Note
When this documentation speaks about “attrs attributes” it means those attributes that are defined using attr.ib() in the class body.
What follows is the API explanation, if you’d like a more hands-on introduction, have a look at Examples.
Core¶
-
attr.s(these=None, repr_ns=None, repr=True, cmp=True, hash=True, init=True, slots=False)¶ A class decorator that adds dunder-methods according to the specified attributes using
attr.ib()or the these argument.Parameters: - these (class:dict of
strtoattr.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 (e.g. if you want to useproperties).If these is not None, the class body is ignored.
- repr_ns – 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
reproutput. - repr (bool) – Create a
__repr__method with a human readable represantation ofattrsattributes.. - cmp (bool) – Create
__eq__,__ne__,__lt__,__le__,__gt__, and__ge__methods that compare the class as if it were a tuple of itsattrsattributes. But the attributes are only compared, if the type of both classes is identical! - hash (bool) – Create a
__hash__method that returns thehash()of a tuple of allattrsattribute values. - init (bool) – Create a
__init__method that initialiazes theattrsattributes. Leading underscores are stripped for the argument name. - slots (bool) – Create a slots-style class that’s more memory-efficient. See Slots for further ramifications.
Note
attrsalso comes with a less playful aliasattr.attributes.For example:
>>> import attr >>> @attr.s ... class C(object): ... _private = attr.ib() >>> C(private=42) C(_private=42) >>> class D(object): ... 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)
- these (class:dict of
-
attr.ib(default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True, convert=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.) – 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 an instance ofFactory, it callable will be use to construct a new value (useful for mutable datatypes like lists or dicts). - validator (callable) –
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.
They can be globally disabled and re-enabled using
get_run_validators(). - repr (bool) – Include this attribute in the generated
__repr__method. - cmp (bool) – Include this attribute in the generated comparison methods
(
__eq__et al). - hash (bool) – Include this attribute in the generated
__hash__method. - init (bool) – Include this attribute in the generated
__init__method. It is possible to set this toFalseand set a default value. In that case this attributed is unconditionally initialized with the specified default value or factory. - convert (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.
Note
attrsalso comes with a less playful aliasattr.attr.- default (Any value.) – Value that is used if an
-
class
attr.Attribute(**kw)¶ Read-only representation of an attribute.
Attribute name: The name of the attribute. Plus all arguments of
attr.ib().Instances of this class are frequently used for introspection purposes like:
- Class attributes on
attrs-decorated classes after@attr.shas been applied. fields()returns a tuple of them.- Validators get them passed as the first argument.
Warning
You should never instantiate this class yourself!
>>> import attr >>> @attr.s ... class C(object): ... x = attr.ib() >>> C.x Attribute(name='x', default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True, convert=None)
- Class attributes on
-
attr.make_class(name, attrs, **attributes_arguments)¶ A quick way to create a new class called name with attrs.
Parameters: Returns: A new class with attrs.
Return type: 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=[])
Helpers¶
attrs comes with a bunch of helper methods that make the work with it easier:
-
attr.fields(cl)¶ Returns the tuple of
attrsattributes for a class.Parameters: cl (class) – Class to introspect.
Raises: - TypeError – If cl is not a class.
- ValueError – If cl is not an
attrsclass.
Return type: tuple of
attr.AttributeFor example:
>>> @attr.s ... class C(object): ... x = attr.ib() ... y = attr.ib() >>> attr.fields(C) (Attribute(name='x', default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True, convert=None), Attribute(name='y', default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True, convert=None))
-
attr.has(cl)¶ Check whether cl is a class with
attrsattributes.Parameters: cl (type) – Class to introspect. Raises: TypeError – If cl is not a class. Return type: boolFor example:
>>> @attr.s ... class C(object): ... pass >>> attr.has(C) True >>> attr.has(object) False
-
attr.asdict(inst, recurse=True, filter=None, dict_factory=<class 'dict'>)¶ Return the
attrsattribute values of i as a dict. Optionally recurse into otherattrs-decorated classes.Parameters: - inst – Instance of a
attrs-decorated class. - recurse (bool) – Recurse into classes that are also
attrs-decorated. - filter (callable) – A callable whose return code deteremines whether an
attribute or element is included (
True) or dropped (False). Is called with theattr.Attributeas 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.
Return type: New in version 16.0.0: dict_factory
For example:
>>> @attr.s ... class C(object): ... x = attr.ib() ... y = attr.ib() >>> attr.asdict(C(1, C(2, 3))) {'y': {'y': 3, 'x': 2}, 'x': 1}
- inst – Instance of a
attrs comes with some handy helpers for filtering:
-
attr.filters.include(*what)¶ Whitelist what.
Parameters: what ( listoftypeorattr.Attributes.) – What to whitelist.Return type: callable
-
attr.filters.exclude(*what)¶ Blacklist what.
Parameters: what ( listof classes orattr.Attributes.) – What to blacklist.Return type: callable
-
attr.assoc(inst, **changes)¶ Copy inst and apply changes.
Parameters: - inst – Instance of a class with
attrsattributes. - changes – Keyword changes in the new copy.
Returns: A copy of inst with changes incorporated.
For example:
>>> @attr.s ... class C(object): ... x = attr.ib() ... y = attr.ib() >>> i1 = C(1, 2) >>> i1 C(x=1, y=2) >>> i2 = attr.assoc(i1, y=3) >>> i2 C(x=1, y=3) >>> i1 == i2 False
- inst – Instance of a class with
-
attr.validate(inst)¶ Validate all attributes on inst that have a validator.
Leaves all exceptions through.
Parameters: inst – Instance of a class with attrsattributes.For example:
>>> @attr.s ... class C(object): ... x = attr.ib(validator=attr.validators.instance_of(int)) >>> i = C(1) >>> i.x = "1" >>> attr.validate(i) Traceback (most recent call last): ... TypeError: ("'x' must be <type 'int'> (got '1' that is a <type 'str'>).", Attribute(name='x', default=NOTHING, validator=<instance_of validator for type <type 'int'>>, repr=True, cmp=True, hash=True, init=True), <type 'int'>, '1')
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.
-
attr.get_run_validators()¶ Return whether or not validators are run.
Validators¶
attrs comes with some common validators within the attrs.validators module:
-
attr.validators.instance_of(type)¶ A validator that raises a
TypeErrorif the initializer is called with a wrong type for this particular attribute (checks are perfomed usingisinstance()therefore it’s also valid to pass a tuple of types).Parameters: type (type or tuple of types) – The type to check for. The
TypeErroris raised with a human readable error message, the attribute (of typeattr.Attribute), the expected type, and the value it got.For example:
>>> @attr.s ... class C(object): ... x = attr.ib(validator=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 '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=True, init=True), <type 'int'>, None)
-
attr.validators.provides(interface)¶ A validator that raises a
TypeErrorif 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. The
TypeErroris raised with a human readable error message, the attribute (of typeattr.Attribute), the expected interface, and the value it got.
-
attr.validators.optional(validator)¶ A validator that makes an attribute optional. An optional attribute is one which can be set to
Nonein addition to satisfying the requirements of the sub-validator.Parameters: validator – A validator that is used for non- Nonevalues.For example:
>>> @attr.s ... class C(object): ... x = attr.ib(validator=attr.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 'int'>, '42') >>> C(None) C(x=None)