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

Comments

Projects
None yet
3 participants
@bluetech

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

This comment has been minimized.

Member

hynek commented Feb 8, 2017

That looks interesting indeed!

@hynek hynek added the Feature label Feb 10, 2017

@hynek

This comment has been minimized.

Member

hynek commented Feb 11, 2017

fixed in 37d38c4

@hynek hynek closed this Feb 11, 2017

@xguse

This comment has been minimized.

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

This comment has been minimized.

bluetech commented Sep 19, 2017

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

@hynek

This comment has been minimized.

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