Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run attribute validator only after __attrs_post_init__ ends

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.

like image 965
zhukovgreen Avatar asked May 16 '26 01:05

zhukovgreen


1 Answers

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.

like image 168
hynek Avatar answered May 19 '26 04:05

hynek