Skip to content

Ability to customize from_dict per data class - #122

Open
trojkat wants to merge 3 commits into
konradhalas:masterfrom
trojkat:master
Open

trojkat wants to merge 3 commits into
konradhalas:masterfrom
trojkat:master

Conversation

@trojkat

@trojkat trojkat commented Dec 9, 2020 •

Copy link
Copy Markdown

In some cases when loading a nested structure of data classes you might need to do a customization for some of them. This change allows customizing a from_dict method for each data class.

Code sample from the test

@dataclass
class X:
    d: date
    t: str

    def from_dict(data_class, data, config):
        data["t"] = "prefix {}".format(data["t"])
        return from_dict(
            data_class=data_class,
            data=data,
            config=Config(type_hooks={date: date.fromtimestamp}),
        )

@dataclass
class Y:
    d: date
    x: X

@GeoloeG-IsT

Copy link
Copy Markdown

would be nice indeed!

Comment thread tests/core/test_config.py
t: str

def from_dict(data_class, data, config):
data["t"] = "prefix {}".format(data["t"])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This prefix can be done with the builtin __post_init__ too

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but this is just an example. The main goal is to have a place to reshape the dictionary before we create a data class from it.

@mwerlberger

Copy link
Copy Markdown

Is there any plan to land these changes? I would very much like this feature to be landed. Or is there a good workaround to achieve the same behavior?

@trojkat

trojkat commented Oct 27, 2021

Copy link
Copy Markdown
Author

@mwerlberger you can use my fork for now https://pypi.org/project/tonalite/

@trojkat

trojkat commented Jan 28, 2023

Copy link
Copy Markdown
Author

@konradhalas I've updated the MR as I can see some life in this repository again.

@trojkat

trojkat commented Feb 28, 2025

Copy link
Copy Markdown
Author

@mciszczon can we merge this feature?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants