python-attrs / python-attrs/cattrs

Check if the data can be structured without actually structuring it

Open
#414 7 comments 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 version: 22.2.0
  • Python version: 3.10
  • Operating System: Windows 10
Description

I have a dataclass that can be instantiated (structured) with a from_dict method, in this way I know all the typings are correct:

from dataclasses import Field, asdict, dataclass, fields
from cattrs import Converter

@dataclass
class MyDataClass:
    a: str
    b: int

    def validate_types(self) -> None:
        self.from_dict(asdict(self))

    @classmethod
    def from_dict(cls, data: dict, converter: Converter = get_converter()):
        return converter.structure(data, cls)

It also has a validate_types method that can be run after instantiation

What I Did

I would like to add the validate_types in the post_init:

from dataclasses import Field, asdict, dataclass, fields
from cattrs import Converter

@dataclass
class MyDataClass:
    a: str
    b: int

    def __post_init__(self):
        self.validate_types()

    def validate_types(self) -> None:
        self.from_dict(asdict(self))

    @classmethod
    def from_dict(cls, data: dict, converter: Converter = get_converter()):
        return converter.structure(data, cls)

unfortunately this ends in an infinite loop, because the from_dict generates a new instance of the class and the code goes into the post_init which calls validate_types, which calls from_dict, which creates a new instance of the class which goes into the post_init and on and on.

would it be possible for you to expose a function/method of the converter that only checks if the data can be structured without actually structuring/creating the new instance?

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 with Converter.structure and the example's from_dict and post_init flow to understand where recursive instance creation occurs. Define what a non-structuring validation operation should guarantee, then verify the behavior against the dataclass example and its recursive case.

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
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.