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

Apply convert/validator also when setting attributes later #256

Closed
blueyed opened this issue Sep 30, 2017 · 3 comments
Closed

Apply convert/validator also when setting attributes later #256

blueyed opened this issue Sep 30, 2017 · 3 comments

Comments

@blueyed
Copy link
Member

blueyed commented Sep 30, 2017

Based on the doc example:

In [2]: import attr
In [3]: @attr.s
   ...: ... class C(object):
   ...: ...     x = attr.ib()
   ...: ...     y = attr.ib()
   ...: ...     @x.validator
   ...: ...     def name_can_be_anything(self, attribute, value):
   ...: ...         if value < 0:
   ...: ...             raise ValueError("x must be positive")
   ...: ...     @y.default
   ...: ...     def name_does_not_matter(self):
   ...: ...         return self.x + 1
   ...:     
In [5]: c = C(1)
In [6]: c.x = -1

I would like the c.x = -1 to also get validated.

My use case at hand is invalidating a cache in case an attribute gets changed, and I've tried validator and convert for this, but both seem to only get applied at __init__ time?!

@blueyed
Copy link
Member Author

blueyed commented Sep 30, 2017

For my use case it is good to use __setattr__:

    def __setattr__(self, name, value):
        if name == 'foo':
            self._foo_data = None
        super(Bar, self).__setattr__(name, value)

But it still feels weird that validators / converters are skipped when setting an attribute later?!

@hynek
Copy link
Member

hynek commented Oct 2, 2017

This is related to #233. Long story short, when I’ve implemented validators, I didn’t want to fuzz with __setattr__ although I already had it working. That ship has sailed after we implemented frozen classes, but someone has to take the time to implement this whole thing properly (see my thoughts on #233).

@blueyed
Copy link
Member Author

blueyed commented Oct 2, 2017

Great, closing it in favor of #233 then.

@blueyed blueyed closed this as completed Oct 2, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants