3

I have:

@attr.s
class Example:
    number = attr.ib(validator=attr.validators.instance_of(int), init=False)

    def __attrs_post_init__(self):
        self.number = 'string'
        print('It seems, validation was running before:(')


t = Example()

How properly setup validation here? I want to validate self.number after instantiation.

2

1 Answer 1

11

There was a bit of a discussion when we implemented __attrs_post_init__ whether to run validators before or after __init__.

We decided for before, because their main raison d'être is to protect the class from wrong instantiation and giving you the confidence about what's in your attributes.


That said, you can always run validators manually using attr.validate():

@attr.s
class Example:
    number = attr.ib(validator=attr.validators.instance_of(int), init=False)

    def __attrs_post_init__(self):
        self.number = 'string'
        # ...
        attr.validate(self)

We do plan on making validation – and when it's performed – more flexible but nothing concrete came out of it yet.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.