From 225715ee60870e21b28f4c35de6031cd85eab390 Mon Sep 17 00:00:00 2001 From: iamdatvt94 <18534522+iamdatvt94@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:51:49 +0700 Subject: [PATCH] Document when on_setattr hooks run --- docs/init.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/init.md b/docs/init.md index 8d5f2610f..13ef010b3 100644 --- a/docs/init.md +++ b/docs/init.md @@ -523,6 +523,24 @@ If present, the hooks are executed in the following order: Notably this means, that you can access all attributes from within your validators, but your converters have to deal with invalid values and have to return a valid value. +The generated `__init__` initializes fields directly, so it skips `on_setattr` hooks. +Those hooks run on assignments such as `obj.x = value`. +Use a converter to transform a value during initialization or a validator to check it. + +```{doctest} +>>> def double_on_assignment(instance, attribute, value): +... return value * 2 +>>> @define +... class Counter: +... count: int = field(on_setattr=double_on_assignment) +>>> counter = Counter(3) +>>> counter.count +3 +>>> counter.count = 3 +>>> counter.count +6 +``` + ## Derived Attributes