-
-
Notifications
You must be signed in to change notification settings - Fork 45
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 from_* functions to parse without inheritance for nested structures #108
Comments
This is something I've been asked for many times. I do have plans to do this, but I haven't yet figured out what a practical and customizable method builder should look like. Maybe you have some ideas. Related issue: |
I'm not at all familiar with all the customizations provided by this module, however if I had to hack in support for this I'd start by making a recursive function to swap out all the dataclasses in a dataclass by serializable ones using the method I proposed in the issue post. I would personally not bother much with all the customization options for now since if your use case is very specific you'd probably be better off by doing this the "proper" way and defining the structures yourself. |
@fakuivan It will work now with #131 merged A more practical way could be as follows: from dataclasses import dataclass
from typing import Callable, Type, TypeVar
from mashumaro.core.meta.code.builder import CodeBuilder
from mashumaro.mixins.yaml import default_decoder, default_encoder
T = TypeVar("T")
def from_yaml(type_: Type[T]) -> Callable[[str], T]:
cb = CodeBuilder(type_, format_name="yaml", decoder=default_decoder)
cb.add_unpack_method()
return getattr(type_, "__mashumaro_from_yaml__")
@dataclass
class MySection:
field: str
@dataclass
class MyConfig:
section: MySection
data = """
section:
field: foobar
"""
print(from_yaml(MyConfig)(data)). # MyConfig(section=MySection(field='foobar')) I know it's still a workaround and there's still a few kinks to work out, but it's a start. |
Good news everyone! I’m working on it, so this functionality will be a part of 3.11 release. |
The long-awaited pull request has landed! |
Is your feature request related to a problem? Please describe.
I'd like to switch from dacite to this, but that would entail modifying every class on a structure to inherit from a specific mixin.
Describe the solution you'd like
It'd be great to have functions in the family of
from_*
that could be called on plain dataclasses to generate a compiled parsing function.Describe alternatives you've considered
I've tried a more naive approach but it does not work for nested structures.
The text was updated successfully, but these errors were encountered: