on_setattr doesn't apply during init
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 20/100
- Issue type
- Feature
- Clarity
- Needs clarification
- Activity status
- Stale
- Tech stack
- python
- Domain
- developer-experience
Research direction
Start by reproducing the minimal Test example and compare construction with post-instantiation assignment. Then trace the on_setattr and initialization entry points in the attrs package and review the existing tests and documentation for validators. Done means the intended behavior for validation during init is decided and covered by a documented, tested approach.
Written by the indexing model from the issue text.
Description
This may be by design, but I was hopeful it would work. When an attribute is set during init, on_setattr does not seem to apply, but it does after instantiation. What's the best way to hook in so I can add a validator to all Attributes? Looking to essentially create a class that enforces all values are set to valid types, without adding the same validator to each attribute when I can have some classes with dozens of attributes.
import attr
def raise_value_error(instance, attribute, value):
raise ValueError
@attr.define(on_setattr=raise_value_error)
class Test:
a: int
test = Test("a string") # fine
test.a = "another string" # fails
- Dominant language
- Python
- Stars
- 5.8k
- Forks
- 480
- Avg merge
- 2h 15m
- Merged PRs (30d)
- 2
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.
More from python-attrs/attrs
-
Difficulty 5/5 Over a week Newbie friendliness 20/100
python-attrs/attrs#1620 ·
-
Difficulty 3/5 1-2 days Newbie friendliness 55/100
python-attrs/attrs#1596 · 2 comments · 1 reaction ·
-
Difficulty 4/5 3-5 days Newbie friendliness 35/100
python-attrs/attrs#1549 · 3 comments ·
-
Difficulty 4/5 3-5 days Newbie friendliness 38/100
python-attrs/attrs#1543 · 2 comments ·
-
Difficulty 4/5 3-5 days Newbie friendliness 35/100
python-attrs/attrs#1532 ·
All issues in python-attrs/attrs
Similar issues
-
triage/confirmed
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
agentscope-ai/agentscope#2775 ·
-
comp/desktop P3 type/bug
Difficulty 1/5 Under an hour Newbie friendliness 92/100
NousResearch/hermes-agent#118866 ·
-
bug
Difficulty 1/5 Under an hour Newbie friendliness 90/100
apache/cloudstack#14222 ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 82/100