Document validator syntax more prominently

This commit is contained in:
Hynek Schlawack 2017-05-22 16:42:40 -07:00
parent 8ed593b954
commit 04e171aa4c
2 changed files with 25 additions and 1 deletions

View File

@ -50,8 +50,27 @@ Core
``attrs`` also comes with a serious business alias ``attr.attrib``.
The object returned by :func:`attr.ib` also has a method called ``validator()`` that can be used as a decorator *within the class body* to define inline validators (see :ref:`examples_validators`).
The object returned by :func:`attr.ib` also allows for setting the default and the validator using decorators:
.. doctest::
>>> @attr.s
... class C(object):
... x = attr.ib()
... y = attr.ib()
... @x.validator
... def name_can_be_anything(self, attribute, value):
... if value < 0:
... raise ValueError("x must be positive")
... @y.default
... def name_does_not_matter(self):
... return self.x + 1
>>> C(1)
C(x=1, y=2)
>>> C(-1)
Traceback (most recent call last):
...
ValueError: x must be positive
.. autoclass:: attr.Attribute

View File

@ -76,6 +76,8 @@ def attr(default=NOTHING, validator=None,
*must* be supplied when instantiating; otherwise a :exc:`TypeError`
will be raised.
The default can also be set using decorator notation as shown below.
:type default: Any value.
:param validator: :func:`callable` that is called by ``attrs``-generated
@ -91,6 +93,9 @@ def attr(default=NOTHING, validator=None,
Validators can be globally disabled and re-enabled using
:func:`get_run_validators`.
The validator can also be set using decorator notation as shown below.
:type validator: ``callable`` or a ``list`` of ``callable``\ s.
:param bool repr: Include this attribute in the generated ``__repr__``