Skip to content

[Feature Request] Add on_change similar to on_setattr, but called after updating the instance. #1437

Open
@burnpanck

Description

@burnpanck

I have been trying to implement a reactive change notification system on top of attrs using on_setattr handlers. However, on_setattr handlers are called before the value is assigned, in order to allow them to perform data conversion. For a reactive change notification, this is subobtimal: you want the changes to be notified after value assignment, so that handlers can inspect the new state on the object. This is especially important when change handlers chain, e.g. when a change handler on an attribute a potentially triggers a change in b, and a change handler on b may want to inspect a, which would otherwise be inconsistent.

Implementing that using the existing mechanisms in attrs proved quite difficult; you'd need a custom __setattr__. However, that immediately prevents any on_setattr behaviour (such as frozen attributes), which requires an attrs-built __setattr__. Thus, one would have to collect all on_setattr specifications on all fields and replace them with custom metadata, which can then be collected into the handling of the custom __setattr__. Obviously, that is suboptimal.

I therefore propose to add another handler on_change, which behaves similar to on_setattr, but is invoked after the value is assigned to the instance. Preferably, in addition to the values provided to on_setattr handlers, we would also supply the previous value (without making any guarantees for concurrent multi-threaded access).

If there is interest in this, I'm happy to whip up a PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions