Skip to content

Allowing to transform the attributes in properties to implement validation in setters #160

@smarie

Description

@smarie

Dear attrs community members

One thing I implemented in autoclass that I feel is missing in attrs is the ability to automatically generate the property setter that includes validation. This might be optional, for example

import attr
from attr.validators import instance_of
@attr.s(validation_setters=True)
class C(object):
     x = attr.ib(validator=instance_of(float))

would transform x into a property (+ a private field) behind the scenes, equivalent to

@attr.s(these={'_x': attr.ib(validator=instance_of(float))})
class C(object):

    @property
    def x(self):
        return self._x

    @x.setter
    def set_x(self, val):
        x_attr = attr.fields(C).x
        x_attr.validator(self, x_attr, val)
        self._x = val

Note that the above code right now throws an AttributeError: can't set attribute so this would need to be fixed first.

Do you think that it would make sense to add this feature ?

Thanks !

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions