Reputation: 1648
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.
Upvotes: 3
Views: 1825
Reputation: 4146
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.
Upvotes: 11