python-attrs / python-attrs/attrs
Create validators not tied to attributes
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 5.8k
- Forks
- 480
- Avg merge
- 2h 15m
- Merged PRs (30d)
- 2
Description
Currently if I need to add a validator to check a condition that affects two attributes, I have to make it a validator of one of them. For example:
@attr.s
class C(object):
x = attr.ib()
y = attr.ib()
@x.validator
def x_smaller_than_y(self, _ , value):
if value >= self.y:
raise ValueError("'x' has to be smaller than 'y'!")
This feels a little unintuitive because this validator is not really a validator on just 'x'. It should be a validator on 'x' and 'y'. It made me wonder if the order of writing x and y in the class matters, in case the validator is run right after an attribute is set.
I wonder what folks think about a generic validator of this form:
@attr.s
class C(object):
x = attr.ib()
y = attr.ib()
@validator
def x_smaller_than_y(self):
if self.x >= self.y:
raise ValueError("'x' has to be smaller than 'y'!")
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The issue names no files or tests; start by reviewing the existing attribute-bound validator behavior shown through @x.validator. Compare it with the proposed class-level @validator and determine how cross-attribute checks should run. Done means a generic validator can enforce the relationship between x and y without being attached to only one attribute, with the behavior covered by tests.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100