python-attrs / python-attrs/attrs

instance_of validator cannot refer to the current class

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

Nobody has claimed this yet.

Feature
Dominant language
Python
Stars
5.8k
Forks
480
Avg merge
2h 15m
Merged PRs (30d)
2

Description

Hi,

I'm working on a project where it's useful for an attribute to refer to the current class. Currently, I'm using something like:

from __future__ import annotations  # Needed for recursive type annotations.


@attr.s(slots=True)
class Namespace(object):
    parent: Namespace = attr.ib(
        validator=lambda inst, attr_, val: attr.validators.instance_of(Namespace)(inst, attr_, val)
    )

Is there currently a better way to do this?
If not, would you be open to a pull request that might allow something like this?

validator = attr.validators.instance_of(type_getter=lambda: Namespace)

(Also, if you have other suggestions for an approach, I'd be happy to implement those in a PR instead.)

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.

Research direction

Start by reading the validator implementation and its existing tests, then trace how instance_of resolves the expected type. Compare the proposed type_getter approach with the current lambda workaround; done means current-class references can be validated without the workaround and existing behavior remains covered.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.