Create a new :term:`field` / :term:`attribute` on a class. .. warning:: Does **nothing** unless the class is also decorated with `attrs.define` (or similar)! Args: default: A value that is used if an *attrs*-generated ``__init__`` is used
(
*,
default=NOTHING,
validator=None,
repr=True,
hash=None,
init=True,
metadata=None,
type=None,
converter=None,
factory=None,
kw_only=None,
eq=None,
order=None,
on_setattr=None,
alias=None,
)
| 435 | |
| 436 | |
| 437 | def field( |
| 438 | *, |
| 439 | default=NOTHING, |
| 440 | validator=None, |
| 441 | repr=True, |
| 442 | hash=None, |
| 443 | init=True, |
| 444 | metadata=None, |
| 445 | type=None, |
| 446 | converter=None, |
| 447 | factory=None, |
| 448 | kw_only=None, |
| 449 | eq=None, |
| 450 | order=None, |
| 451 | on_setattr=None, |
| 452 | alias=None, |
| 453 | ): |
| 454 | """ |
| 455 | Create a new :term:`field` / :term:`attribute` on a class. |
| 456 | |
| 457 | .. warning:: |
| 458 | |
| 459 | Does **nothing** unless the class is also decorated with |
| 460 | `attrs.define` (or similar)! |
| 461 | |
| 462 | Args: |
| 463 | default: |
| 464 | A value that is used if an *attrs*-generated ``__init__`` is used |
| 465 | and no value is passed while instantiating or the attribute is |
| 466 | excluded using ``init=False``. |
| 467 | |
| 468 | If the value is an instance of `attrs.Factory`, its callable will |
| 469 | be used to construct a new value (useful for mutable data types |
| 470 | like lists or dicts). |
| 471 | |
| 472 | If a default is not set (or set manually to `attrs.NOTHING`), a |
| 473 | value *must* be supplied when instantiating; otherwise a |
| 474 | `TypeError` will be raised. |
| 475 | |
| 476 | .. seealso:: `defaults` |
| 477 | |
| 478 | factory (~typing.Callable): |
| 479 | Syntactic sugar for ``default=attr.Factory(factory)``. |
| 480 | |
| 481 | validator (~typing.Callable | list[~typing.Callable]): |
| 482 | Callable that is called by *attrs*-generated ``__init__`` methods |
| 483 | after the instance has been initialized. They receive the |
| 484 | initialized instance, the :func:`~attrs.Attribute`, and the passed |
| 485 | value. |
| 486 | |
| 487 | The return value is *not* inspected so the validator has to throw |
| 488 | an exception itself. |
| 489 | |
| 490 | If a `list` is passed, its items are treated as validators and must |
| 491 | all pass. |
| 492 | |
| 493 | Validators can be globally disabled and re-enabled using |
| 494 | `attrs.validators.get_disabled` / `attrs.validators.set_disabled`. |