| 1 |
# Extending |
| 2 |
|
| 3 |
Each *attrs*-decorated class has a `__attrs_attrs__` class attribute. |
| 4 |
It's a tuple of {class}`attrs.Attribute` carrying metadata about each attribute. |
| 5 |
|
| 6 |
So it is fairly simple to build your own decorators on top of *attrs*: |
| 7 |
|
| 8 |
```{doctest} |
| 9 |
>>> from attr import define |
| 10 |
>>> def print_attrs(cls): |
| 11 |
... print(cls.__attrs_attrs__) |
| 12 |
... return cls |
| 13 |
>>> @print_attrs |
| 14 |
... @define |
| 15 |
... class C: |
| 16 |
... a: int |
| 17 |
(Attribute(name='a', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=<class 'int'>, converter=None, kw_only=False, inherited=False, on_setattr=None, alias='a'),) |
| 18 |
``` |
| 19 |
|
| 20 |
:::{warning} |
| 21 |
The {func}`attrs.define` / {func}`attr.s` decorator **must** be applied first because it puts `__attrs_attrs__` in place! |
| 22 |
That means that is has to come *after* your decorator because: |
| 23 |
|
| 24 |
```python |
| 25 |
@a |
| 26 |
@b |
| 27 |
def f(): |
| 28 |
pass |
| 29 |
``` |
| 30 |
|
| 31 |
is just [syntactic sugar](https://en.wikipedia.org/wiki/Syntactic_sugar) for: |
| 32 |
|
| 33 |
```python |
| 34 |
def original_f(): |
| 35 |
pass |
| 36 |
|
| 37 |
f = a(b(original_f)) |
| 38 |
``` |
| 39 |
::: |
| 40 |
|
| 41 |
|
| 42 |
## Wrapping the Decorator |
| 43 |
|
| 44 |
A more elegant way can be to wrap *attrs* altogether and build a class [DSL](https://en.wikipedia.org/wiki/Domain-specific_language) on top of it. |
| 45 |
|
| 46 |
An example for that is the package [*environ-config*](https://github.com/hynek/environ-config) that uses *attrs* under the hood to define environment-based configurations declaratively without exposing *attrs* APIs at all. |
| 47 |
|
| 48 |
Another common use case is to overwrite *attrs*'s defaults. |
| 49 |
|
| 50 |
|
| 51 |
### Mypy |
| 52 |
|
| 53 |
Unfortunately, decorator wrapping currently [confuses](https://github.com/python/mypy/issues/5406) mypy's *attrs* plugin. |
| 54 |
At the moment, the best workaround is to hold your nose, write a fake *Mypy* plugin, and mutate a bunch of global variables: |
| 55 |
|
| 56 |
```python |
| 57 |
from mypy.plugin import Plugin |
| 58 |
from mypy.plugins.attrs import ( |
| 59 |
attr_attrib_makers, |
| 60 |
attr_class_makers, |
| 61 |
attr_dataclass_makers, |
| 62 |
) |
| 63 |
|
| 64 |
# These work just like `attr.dataclass`. |
| 65 |
attr_dataclass_makers.add("my_module.method_looks_like_attr_dataclass") |
| 66 |
|
| 67 |
# This works just like `attr.s`. |
| 68 |
attr_class_makers.add("my_module.method_looks_like_attr_s") |
| 69 |
|
| 70 |
# These are our `attr.ib` makers. |
| 71 |
attr_attrib_makers.add("my_module.method_looks_like_attrib") |
| 72 |
|
| 73 |
class MyPlugin(Plugin): |
| 74 |
# Our plugin does nothing but it has to exist so this file gets loaded. |
| 75 |
pass |
| 76 |
|
| 77 |
|
| 78 |
def plugin(version): |
| 79 |
return MyPlugin |
| 80 |
``` |
| 81 |
|
| 82 |
Then tell *Mypy* about your plugin using your project's `mypy.ini`: |
| 83 |
|
| 84 |
```ini |
| 85 |
[mypy] |
| 86 |
plugins=<path to file> |
| 87 |
``` |
| 88 |
|
| 89 |
:::{warning} |
| 90 |
Please note that it is currently *impossible* to let mypy know that you've changed defaults like *eq* or *order*. |
| 91 |
You can only use this trick to tell *Mypy* that a class is actually an *attrs* class. |
| 92 |
::: |
| 93 |
|
| 94 |
|
| 95 |
### Pyright |
| 96 |
|
| 97 |
Generic decorator wrapping is supported in [*Pyright*](https://github.com/microsoft/pyright) via `typing.dataclass_transform` / {pep}`689`. |
| 98 |
|
| 99 |
For a custom wrapping of the form: |
| 100 |
|
| 101 |
``` |
| 102 |
@typing.dataclass_transform(field_specifiers=(attr.attrib, attr.field)) |
| 103 |
def custom_define(f): |
| 104 |
return attr.define(f) |
| 105 |
``` |
| 106 |
|
| 107 |
## Types |
| 108 |
|
| 109 |
*attrs* offers two ways of attaching type information to attributes: |
| 110 |
|
| 111 |
- {pep}`526` annotations, |
| 112 |
- and the *type* argument to {func}`attr.ib`. |
| 113 |
|
| 114 |
This information is available to you: |
| 115 |
|
| 116 |
```{doctest} |
| 117 |
>>> from attr import attrib, define, field, fields |
| 118 |
>>> @define |
| 119 |
... class C: |
| 120 |
... x: int = field() |
| 121 |
... y = attrib(type=str) |
| 122 |
>>> fields(C).x.type |
| 123 |
<class 'int'> |
| 124 |
>>> fields(C).y.type |
| 125 |
<class 'str'> |
| 126 |
``` |
| 127 |
|
| 128 |
Currently, *attrs* doesn't do anything with this information but it's very useful if you'd like to write your own validators or serializers! |
| 129 |
|
| 130 |
(extending-metadata)= |
| 131 |
|
| 132 |
## Metadata |
| 133 |
|
| 134 |
If you're the author of a third-party library with *attrs* integration, you may want to take advantage of attribute metadata. |
| 135 |
|
| 136 |
Here are some tips for effective use of metadata: |
| 137 |
|
| 138 |
- Try making your metadata keys and values immutable. |
| 139 |
This keeps the entire {class}`~attrs.Attribute` instances immutable too. |
| 140 |
|
| 141 |
- To avoid metadata key collisions, consider exposing your metadata keys from your modules.: |
| 142 |
|
| 143 |
```python |
| 144 |
from mylib import MY_METADATA_KEY |
| 145 |
|
| 146 |
@define |
| 147 |
class C: |
| 148 |
x = field(metadata={MY_METADATA_KEY: 1}) |
| 149 |
``` |
| 150 |
|
| 151 |
Metadata should be composable, so consider supporting this approach even if you decide implementing your metadata in one of the following ways. |
| 152 |
|
| 153 |
- Expose `field` wrappers for your specific metadata. |
| 154 |
This is a more graceful approach if your users don't require metadata from other libraries. |
| 155 |
|
| 156 |
```{doctest} |
| 157 |
>>> from attrs import fields, NOTHING |
| 158 |
>>> MY_TYPE_METADATA = '__my_type_metadata' |
| 159 |
>>> |
| 160 |
>>> def typed( |
| 161 |
... cls, default=NOTHING, validator=None, repr=True, |
| 162 |
... eq=True, order=None, hash=None, init=True, metadata=None, |
| 163 |
... converter=None |
| 164 |
... ): |
| 165 |
... metadata = metadata or {} |
| 166 |
... metadata[MY_TYPE_METADATA] = cls |
| 167 |
... return field( |
| 168 |
... default=default, validator=validator, repr=repr, |
| 169 |
... eq=eq, order=order, hash=hash, init=init, |
| 170 |
... metadata=metadata, converter=converter |
| 171 |
... ) |
| 172 |
>>> |
| 173 |
>>> @define |
| 174 |
... class C: |
| 175 |
... x: int = typed(int, default=1, init=False) |
| 176 |
>>> fields(C).x.metadata[MY_TYPE_METADATA] |
| 177 |
<class 'int'> |
| 178 |
``` |
| 179 |
|
| 180 |
(transform-fields)= |
| 181 |
|
| 182 |
## Automatic Field Transformation and Modification |
| 183 |
|
| 184 |
*attrs* allows you to automatically modify or transform the class' fields while the class is being created. |
| 185 |
You do this by passing a *field_transformer* hook to {func}`~attrs.define` (and friends). |
| 186 |
Its main purpose is to automatically add converters to attributes based on their type to aid the development of API clients and other typed data loaders. |
| 187 |
|
| 188 |
This hook must have the following signature: |
| 189 |
|
| 190 |
```{eval-rst} |
| 191 |
.. function:: your_hook(cls: type, fields: list[attrs.Attribute]) -> list[attrs.Attribute] |
| 192 |
:noindex: |
| 193 |
``` |
| 194 |
|
| 195 |
- *cls* is your class right *before* it is being converted into an attrs class. |
| 196 |
This means it does not yet have the `__attrs_attrs__` attribute. |
| 197 |
- *fields* is a list of all `attrs.Attribute` instances that will later be set to `__attrs_attrs__`. |
| 198 |
You can modify these attributes any way you want: |
| 199 |
You can add converters, change types, and even remove attributes completely or create new ones! |
| 200 |
|
| 201 |
For example, let's assume that you really don't like floats: |
| 202 |
|
| 203 |
```{doctest} |
| 204 |
>>> def drop_floats(cls, fields): |
| 205 |
... return [f for f in fields if f.type not in {float, 'float'}] |
| 206 |
... |
| 207 |
>>> @frozen(field_transformer=drop_floats) |
| 208 |
... class Data: |
| 209 |
... a: int |
| 210 |
... b: float |
| 211 |
... c: str |
| 212 |
... |
| 213 |
>>> Data(42, "spam") |
| 214 |
Data(a=42, c='spam') |
| 215 |
``` |
| 216 |
|
| 217 |
A more realistic example would be to automatically convert data that you, e.g., load from JSON: |
| 218 |
|
| 219 |
```{doctest} |
| 220 |
>>> from datetime import datetime |
| 221 |
>>> |
| 222 |
>>> def auto_convert(cls, fields): |
| 223 |
... results = [] |
| 224 |
... for field in fields: |
| 225 |
... if field.converter is not None: |
| 226 |
... results.append(field) |
| 227 |
... continue |
| 228 |
... if field.type in {datetime, 'datetime'}: |
| 229 |
... converter = (lambda d: datetime.fromisoformat(d) if isinstance(d, str) else d) |
| 230 |
... else: |
| 231 |
... converter = None |
| 232 |
... results.append(field.evolve(converter=converter)) |
| 233 |
... return results |
| 234 |
... |
| 235 |
>>> @frozen(field_transformer=auto_convert) |
| 236 |
... class Data: |
| 237 |
... a: int |
| 238 |
... b: str |
| 239 |
... c: datetime |
| 240 |
... |
| 241 |
>>> from_json = {"a": 3, "b": "spam", "c": "2020-05-04T13:37:00"} |
| 242 |
>>> Data(**from_json) # **** |
| 243 |
Data(a=3, b='spam', c=datetime.datetime(2020, 5, 4, 13, 37)) |
| 244 |
``` |
| 245 |
|
| 246 |
Or, perhaps you would prefer to generate dataclass-compatible `__init__` signatures via a default field *alias*. |
| 247 |
Note, *field_transformer* operates on {class}`attrs.Attribute` instances before the default private-attribute handling is applied so explicit user-provided aliases can be detected. |
| 248 |
|
| 249 |
```{doctest} |
| 250 |
>>> def dataclass_names(cls, fields): |
| 251 |
... return [ |
| 252 |
... field.evolve(alias=field.name) |
| 253 |
... if not field.alias |
| 254 |
... else field |
| 255 |
... for field in fields |
| 256 |
... ] |
| 257 |
... |
| 258 |
>>> @frozen(field_transformer=dataclass_names) |
| 259 |
... class Data: |
| 260 |
... public: int |
| 261 |
... _private: str |
| 262 |
... explicit: str = field(alias="aliased_name") |
| 263 |
... |
| 264 |
>>> Data(public=42, _private="spam", aliased_name="yes") |
| 265 |
Data(public=42, _private='spam', explicit='yes') |
| 266 |
``` |
| 267 |
|
| 268 |
## Customize Value Serialization in `asdict()` |
| 269 |
|
| 270 |
*attrs* allows you to serialize instances of *attrs* classes to dicts using the {func}`attrs.asdict` function. |
| 271 |
However, the result can not always be serialized since most data types will remain as they are: |
| 272 |
|
| 273 |
```{doctest} |
| 274 |
>>> import json |
| 275 |
>>> import datetime |
| 276 |
>>> from attrs import asdict |
| 277 |
>>> |
| 278 |
>>> @frozen |
| 279 |
... class Data: |
| 280 |
... dt: datetime.datetime |
| 281 |
... |
| 282 |
>>> data = asdict(Data(datetime.datetime(2020, 5, 4, 13, 37))) |
| 283 |
>>> data |
| 284 |
{'dt': datetime.datetime(2020, 5, 4, 13, 37)} |
| 285 |
>>> json.dumps(data) |
| 286 |
Traceback (most recent call last): |
| 287 |
... |
| 288 |
TypeError: Object of type datetime is not JSON serializable |
| 289 |
``` |
| 290 |
|
| 291 |
To help you with this, {func}`~attrs.asdict` allows you to pass a *value_serializer* hook. |
| 292 |
It has the signature |
| 293 |
|
| 294 |
```{eval-rst} |
| 295 |
.. function:: your_hook(inst: type, field: attrs.Attribute, value: typing.Any) -> typing.Any |
| 296 |
:noindex: |
| 297 |
``` |
| 298 |
|
| 299 |
```{doctest} |
| 300 |
>>> from attr import asdict |
| 301 |
>>> def serialize(inst, field, value): |
| 302 |
... if isinstance(value, datetime.datetime): |
| 303 |
... return value.isoformat() |
| 304 |
... return value |
| 305 |
... |
| 306 |
>>> data = asdict( |
| 307 |
... Data(datetime.datetime(2020, 5, 4, 13, 37)), |
| 308 |
... value_serializer=serialize, |
| 309 |
... ) |
| 310 |
>>> data |
| 311 |
{'dt': '2020-05-04T13:37:00'} |
| 312 |
>>> json.dumps(data) |
| 313 |
'{"dt": "2020-05-04T13:37:00"}' |
| 314 |
``` |