Skip to content

on_setattr doesn't apply during init #672

Open
@liveFreeOrCode

Description

@liveFreeOrCode

This may be by design, but I was hopeful it would work. When an attribute is set during init, on_setattr does not seem to apply, but it does after instantiation. What's the best way to hook in so I can add a validator to all Attributes? Looking to essentially create a class that enforces all values are set to valid types, without adding the same validator to each attribute when I can have some classes with dozens of attributes.

import attr

def raise_value_error(instance, attribute, value):
    raise ValueError

@attr.define(on_setattr=raise_value_error)
class Test:
    a: int

test = Test("a string")  # fine
test.a = "another string"  # fails

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions