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

Add deserialize context to __post_deserialize__ #280

Open
kdkavanagh-jt opened this issue Feb 10, 2025 · 0 comments
Open

Add deserialize context to __post_deserialize__ #280

kdkavanagh-jt opened this issue Feb 10, 2025 · 0 comments

Comments

@kdkavanagh-jt
Copy link

I have a yaml file containing some custom tags like:

sub_config: !include /path/to/my/config

I've updated my yaml.SafeLoader to properly handle those tags, (resolving them to a dictionary in this case) before handing the data off to mashumaro. Those resolvers are able to set an attribute on data["sub_config"] to indicate that it was loaded from an !include tag. I can then detect this in __pre_deserialize__ by inspecting the dict, but I dont currently have a way to set some hidden attr on the resolved object, since I dont have access to that data: dict in __post_deserialize__.

I'd like to carry that metadata thru to the dataclass such that when mashumaro serializes the type back to a yaml file, I can intercept data: dict in __post_deserialize__ and reattach that metadata for my yaml representer to convert back to !include ...

In other words, something like this would do the trick:

@dataclass
class ConfigItem(DataClassYAMLMixin):

  def __post_deserialize(cls, obj: T, data: dict):
           for k,v in data.items():
            if hasattr(v, YAML_INCLUDE_FROM_SOURCE):
               # Copy the attr over from the dict into the final object
               setattr(getattr(obj, k), YAML_INCLUDE_FROM_SOURCE, getattr(v, YAML_INCLUDE_FROM_SOURCE))

A workaround is to do something like this, but this is undesirable as it introduces a new "proper" attribute on the dataclass, making inheritance messy, etc:

@dataclass
class ConfigItem(DataClassYAMLMixin):
    __include_keys__: list[tuple[str, pathlib.Path]]

    @classmethod
    def __pre_deserialize__(cls, data: dict) -> dict: # pylint: disable=arguments-renamed
        inc_keys = data.setdefault("__include_keys__", [])
        for k,v in data.items():
            if hasattr(v, YAML_INCLUDE_FROM_SOURCE):
                inc_keys.append((k, getattr(v, YAML_INCLUDE_FROM_SOURCE)))
        return data

Is there a better way to do this already?

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

No branches or pull requests

1 participant