From 5aea24125a323ca516856cf145b54d9bfb788b69 Mon Sep 17 00:00:00 2001 From: Brian Pugh Date: Fri, 29 Dec 2023 10:48:42 -0500 Subject: [PATCH] Move conditional clause to beginning for validator/converter docs. (#1213) Move conditional clause to beginning for validator/converter docs. Provide converter example. Co-authored-by: Hynek Schlawack --- docs/examples.md | 10 +++++++--- docs/init.md | 3 +++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/examples.md b/docs/examples.md index ed77b3ff..0f8301aa 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -467,7 +467,8 @@ Traceback (most recent call last): TypeError: ("'x' must be (got '42' that is a ).", Attribute(name='x', default=NOTHING, factory=NOTHING, validator=>, type=None, kw_only=False), , '42') ``` -Please note that if you use {func}`attr.s` (and **not** {func}`attrs.define`) to define your class, validators only run on initialization by default -- not when you set an attribute. +If using the old-school {func}`attr.s` decorator, validators only run on initialization by default. +If using the newer {func}`attrs.define` and friends, validators run on initialization *and* on attribute setting. This behavior can be changed using the *on_setattr* argument. Check out {ref}`validators` for more details. @@ -485,10 +486,13 @@ This can be useful for doing type-conversions on values that you don't want to f >>> o = C("1") >>> o.x 1 +>>> o.x = "2" +>>> o.x +2 ``` -Please note that converters only run on initialization when using the old-school {func}`attr.s` decorator. -They do run by default with {func}`attrs.define` and friends. +If using the old-school {func}`attr.s` decorator, converters only run on initialization by default. +If using the newer {func}`attrs.define` and friends, converters run on initialization *and* on attribute setting. This behavior can be changed using the *on_setattr* argument. Check out {ref}`converters` for more details. diff --git a/docs/init.md b/docs/init.md index 0a55f752..4aaa0999 100644 --- a/docs/init.md +++ b/docs/init.md @@ -307,6 +307,9 @@ This can be useful for doing type-conversions on values that you don't want to f >>> o = C("1") >>> o.x 1 +>>> o.x = "2" +>>> o.x +2 ``` Converters are run *before* validators, so you can use validators to check the final form of the value.