on_setattr doesn't apply during init

Open
#672 3 comments 3 reactions 0 assignees View on GitHub

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

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

Documentation

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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python-attrs/attrs

All issues in python-attrs/attrs

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.