Unlike Data Classes, *attrs* doesn't force you to use type annotations.
So, the previous example could also have been written as:
```{doctest}
>>> @define
... class Coordinates:
... x = field()
... y = field()
>>> Coordinates(1, 2)
Coordinates(x=1, y=2)
```
:::{caution}
If a class body contains a field that is defined using {func}`attrs.field` (or {func}`attr.ib`), but **lacks a type annotation**, *attrs* switches to a no-typing mode and ignores fields that have type annotations but are not defined using {func}`attrs.field` (or {func}`attr.ib`).
If you prefer to expose your privates, you can use keyword argument aliases:
```{doctest}
>>> @define
... class C:
... _x: int = field(alias="_x")
>>> C(_x=1)
C(_x=1)
```
An additional way of defining attributes is supported too.
This is useful in times when you want to enhance classes that are not yours (nice `__repr__` for Django models anyone?):
```{doctest}
>>> class SomethingFromSomeoneElse:
... def __init__(self, x):
... self.x = x
>>> SomethingFromSomeoneElse = define(
... these={
... "x": field()
... }, init=False)(SomethingFromSomeoneElse)
>>> SomethingFromSomeoneElse(1)
SomethingFromSomeoneElse(x=1)
```
[Subclassing is bad for you](https://www.youtube.com/watch?v=3MNVP9-hglc), but *attrs* will still do what you'd hope for:
```{doctest}
>>> @define(slots=False)
... class A:
... a: int
... def get_a(self):
... return self.a
>>> @define(slots=False)
... class B:
... b: int
>>> @define(slots=False)
... class C(B, A):
... c: int
>>> i = C(1, 2, 3)
>>> i
C(a=1, b=2, c=3)
>>> i == C(1, 2, 3)
True
>>> i.get_a()
1
```
{term}`Slotted classes <slottedclasses>`, which are the default for the new APIs, don't play well with multiple inheritance so we don't use them in the example.
The order of the attributes is defined by the [MRO](https://www.python.org/download/releases/2.3/mro/).
### Keyword-only Attributes
You can also add [keyword-only](https://docs.python.org/3/glossary.html#keyword-only-parameter) attributes:
If you don't set `kw_only=True`, then there is no valid attribute ordering, and you'll get an error:
```{doctest}
>>> @define
... class A:
... a: int = 0
>>> @define
... class B(A):
... b: int
Traceback (most recent call last):
...
ValueError: No mandatory attributes allowed after an attribute with a default value or factory. Attribute in question: Attribute(name='b', default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, converter=None, metadata=mappingproxy({}), type=int, kw_only=False)
```
(asdict)=
## Converting to Collections Types
When you have a class with data, it often is very convenient to transform that class into a {class}`dict` (for example if you want to serialize it to JSON):
```{doctest}
>>> from attrs import asdict
>>> asdict(Coordinates(x=1, y=2))
{'x': 1, 'y': 2}
```
Some fields cannot or should not be transformed.
For that, {func}`attrs.asdict` offers a callback that decides whether an attribute should be included:
For the common case where you want to [`include`](attrs.filters.include) or [`exclude`](attrs.filters.exclude) certain types, string name or attributes, *attrs* ships with a few helpers:
Though using string names directly is convenient, mistyping attribute names will silently do the wrong thing and neither Python nor your type checker can help you.
{func}`attrs.fields()` will raise an `AttributeError` when the field doesn't exist while literal string names won't.
Using {func}`attrs.fields()` to get attributes is worth being recommended in most cases.
More information on why class methods for constructing objects are awesome can be found in this insightful [blog post](https://web.archive.org/web/20210130220433/http://as.ynchrono.us/2014/12/asynchronous-object-initialization.html).
Default factories can also be set using the `factory` argument to {func}`~attrs.field`, and using a decorator.
The method receives the partially initialized instance which enables you to base a default value on other attributes:
Please keep in mind that the decorator approach *only* works if the attribute in question has a {func}`~attrs.field` assigned to it.
As a result, annotating an attribute with a type is *not* enough if you use `@default`.
(examples-validators)=
## Validators
Although your initializers should do as little as possible (ideally: just initialize your instance according to the arguments!), it can come in handy to do some kind of validation on the arguments.
*attrs* offers two ways to define validators for each attribute and it's up to you to choose which one suits your style and project better.
You can use a decorator:
```{doctest}
>>> @define
... class C:
... x: int = field()
... @x.validator
... def check(self, attribute, value):
... if value > 42:
... raise ValueError("x must be smaller or equal to 42")
... raise ValueError("'x' has to be smaller than 'y'!")
>>> @define
... class C:
... x: int = field(validator=[validators.instance_of(int),
... x_smaller_than_y])
... y: int
>>> C(x=3, y=4)
C(x=3, y=4)
>>> C(x=4, y=3)
Traceback (most recent call last):
...
ValueError: 'x' has to be smaller than 'y'!
```
...or both at once:
```{doctest}
>>> @define
... class C:
... x: int = field(validator=validators.instance_of(int))
... @x.validator
... def fits_byte(self, attribute, value):
... if not 0 <= value <256:
... raise ValueError("value out of bounds")
>>> C(128)
C(x=128)
>>> C("128")
Traceback (most recent call last):
...
TypeError: ("'x' must be <class'int'> (got '128' that is a <class'str'>).", Attribute(name='x', default=NOTHING, validator=[<instance_ofvalidatorfortype<class'int'>>, <functionfits_byteat0x10fd7a0d0>], repr=True, cmp=True, hash=True, init=True, metadata=mappingproxy({}), type=int, converter=None, kw_only=False), <class'int'>, '128')
>>> C(256)
Traceback (most recent call last):
...
ValueError: value out of bounds
```
Please note that the decorator approach only works if -- and only if! -- the attribute in question has a {func}`~attrs.field` assigned.
Therefore if you use `@validator`, it is *not* enough to annotate said attribute with a type.
*attrs* ships with a bunch of validators, make sure to [check them out](api-validators) before writing your own:
... x: int = field(validator=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, factory=NOTHING, validator=<instance_ofvalidatorfortype<type'int'>>, type=None, kw_only=False), <type'int'>, '42')
*attrs* also allows you to associate a type with an attribute using either the *type* argument to using {pep}`526`-annotations or {func}`attrs.field`/{func}`attr.ib`:
If you don't mind annotating *all* attributes, you can even drop the `attrs.field` and assign default values instead:
```{doctest}
>>> import typing
>>> @define
... class AutoC:
... cls_var: typing.ClassVar[int] = 5 # this one is ignored
... l: list[int] = Factory(list)
... x: int = 1
... foo: str = "every attrib needs a type if auto_attribs=True"
... bar: typing.Any = None
>>> fields(AutoC).l.type
list[int]
>>> fields(AutoC).x.type
<class'int'>
>>> fields(AutoC).foo.type
<class'str'>
>>> fields(AutoC).bar.type
typing.Any
>>> AutoC()
AutoC(l=[], x=1, foo='every attrib needs a type if auto_attribs=True', bar=None)
>>> AutoC.cls_var
5
```
The generated `__init__` method will have an attribute called `__annotations__` that contains this type information.
If your annotations contain strings (e.g. forward references),
you can resolve these after all references have been defined by using {func}`attrs.resolve_types`.
This will replace the *type* attribute in the respective fields.
```{doctest}
>>> from attrs import resolve_types
>>> @define
... class A:
... a: 'list[A]'
... b: 'B'
...
>>> @define
... class B:
... a: A
...
>>> fields(A).a.type
'list[A]'
>>> fields(A).b.type
'B'
>>> resolve_types(A, globals(), locals())
<class'A'>
>>> fields(A).a.type
list[A]
>>> fields(A).b.type
<class'B'>
```
:::{note}
If you find yourself using string type annotations to handle forward references, wrap the entire type annotation in quotes instead of only the type you need a forward reference to (so `'list[A]'` instead of `list['A']`).
This is a limitation of the Python typing system.
:::
:::{warning}
*attrs* itself doesn't have any features that work on top of type metadata.
However it's useful for writing your own validators or serialization frameworks.
:::
## Slots
{term}`Slotted classes <slottedclasses>` have several advantages on CPython.
Defining `__slots__` by hand is tedious, in *attrs* it's just a matter of using {func}`attrs.define` or passing `slots=True` to {func}`attr.s`:
You can still have power over the attributes if you pass a dictionary of name: {func}`~attrs.field` mappings and can pass the same arguments as you can to `@attrs.define`:
If you need to dynamically make a class with {func}`~attrs.make_class` and it needs to be a subclass of something else than {class}`object`, use the `bases` argument:
```{doctest}
>>> class D:
... def __eq__(self, other):
... return True # arbitrary example
>>> C = make_class("C", {}, bases=(D,), cmp=False)
>>> isinstance(C(), D)
True
```
Sometimes, you want to have your class's `__init__` method do more than just
the initialization, validation, etc. that gets done for you automatically when
using `@define`.
To do this, just define a `__attrs_post_init__` method in your class.
It will get called at the end of the generated `__init__` method.
```{doctest}
>>> @define
... class C:
... x: int
... y: int
... z: int = field(init=False)
...
... def __attrs_post_init__(self):
... self.z = self.x + self.y
>>> obj = C(x=1, y=2)
>>> obj
C(x=1, y=2, z=3)
```
You can exclude single attributes from certain methods:
```{doctest}
>>> @define
... class C:
... user: str
... password: str = field(repr=False)
>>> C("me", "s3kr3t")
C(user='me')
```
Alternatively, to influence how the generated `__repr__()` method formats a specific attribute, specify a custom callable to be used instead of the `repr()` built-in function: