Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to customize from_dict per data class #122

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

trojkat
Copy link

@trojkat trojkat commented Dec 9, 2020

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

@MeTaNoV
Copy link

MeTaNoV commented Jan 28, 2021

would be nice indeed!

t: str

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

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
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

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
Copy link
Author

trojkat commented Oct 27, 2021

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

@trojkat
Copy link
Author

trojkat commented Jan 28, 2023

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

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