python-attrs / python-attrs/cattrs

validation options when structuring

Open
#307 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
Python
Stars
1.1k
Forks
159
Avg merge
12h 21m
Merged PRs (30d)
6

Description

cattrs validation is exclusively type-based right now from what I've been able to surmise. Is there a plan to extend this to any ability to pass options to structure hook on a per-field basis?

At least for classes using attrs/dataclass they can provide per-field metadata that would be great to expose to the hooks.

@attrs.define
class User:
    id: int = attrs.field(metadata=cattrs.metadata(explicit_type=True))

def cattrs_int(value, type):
    # XXX no way to use the attrs.field metadata here
    return int(value)
cattrs.register_structure_hook(int, cattrs_int)

Allowing me to configure a restriction to avoid casting a string to an int. Note the comment and that the type param is int and not the attrs.field leaving it inaccessible.

In other situations that aren't using attrs/dataclass there's likely a similar desire to define per-field options to the hooks.

Right now the workaround seems to be to define my own custom subclasses which is obviously less than ideal:

class ExplicitInt(int):
    @classmethod
    def from_cattrs_structure(cls, value, type):
        if not isinstance(value, int):
            raise Exception('value is not an int')
        return cls(value)

@attrs.define
class User:
    id: ExplicitInt

cattrs.register_structure_hook(ExplicitInt, ExplicitInt.from_cattrs_structure)

Is there a better way than this?

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

The issue does not name files or tests. Start from cattrs structure-hook registration and the attrs/dataclass field metadata described in the examples, then determine how per-field options could reach a hook. Done would require an agreed design and coverage for the requested validation behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.