Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: nice way to write ad-hoc validators #143

Closed
bluetech opened this issue Feb 8, 2017 · 5 comments
Closed

Proposal: nice way to write ad-hoc validators #143

bluetech opened this issue Feb 8, 2017 · 5 comments
Labels

Comments

@bluetech
Copy link

bluetech commented Feb 8, 2017

Hopefully this wasn't proposed before.

@attr.s
class C(object):
    x = attr.ib()
    y = attr.ib()

    @x.validator                                               
    def x_smaller_than_y(self, attribute, value):
        if value >= self.y:
            raise ValueError("'x' has to be smaller than 'y'!")

If you managed to guess what this does it means the syntax is intuitive enough :)

Similar syntax familiar from property.deleter and friends can also be useful for other parts, but for validators it feels like a natural fit (especially with the recent change to allow multiple validators).

@hynek
Copy link
Member

hynek commented Feb 8, 2017

That looks interesting indeed!

@hynek hynek added the Feature label Feb 10, 2017
@hynek
Copy link
Member

hynek commented Feb 11, 2017

fixed in 37d38c4

@hynek hynek closed this as completed Feb 11, 2017
@xguse
Copy link

xguse commented Sep 19, 2017

My question is: why is attribute included? It is not used in the validator function. What purpose does this serve? How would it be used. The docs at this opint make it seem like this is required for the api to work but it is just ignored in the example given.

Can someone provide an example where attribute is used to illustrate the logic to me?

@bluetech
Copy link
Author

The validator argument to attr.ib, which preceded the decorator, takes the same arguments. So the decorator takes them for consistency.

@hynek
Copy link
Member

hynek commented Sep 20, 2017

Yep that's the reason. Internally they're treated the same. We could add some magic to make it optional I guess but no one bothered so far.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants