konradhalas / dacite

Simple creation of data classes from dictionaries.
MIT License
1.76k stars 106 forks source link

feature request: type hooks for embedded types #124

Closed shaunc closed 3 years ago

shaunc commented 3 years ago

I would like to use a type hook convert a type embedded in a type definition. For example:

class Bar:
    ...

def buildBar(data: Any)-> Bar:
    ...

@dataclass
class Foo:
    bar: Mapping[str, Bar] = field(default_factory: lambda: {})

# should return a `Foo` with `bar` map with `bar1` entry a `Bar`
dacite.from_dict(
    data_class=Foo,
    data={"bar1": {"data": "for bar"}},
    config=dacite.from_dict(type_hooks={Bar: buildBar}))
konradhalas commented 3 years ago

Hi @shaunc - I think we support this case, please try my example:

from dataclasses import dataclass, field
from typing import Any, Mapping

import dacite

class Bar:
    def __init__(self, i: int) -> None:
        self.i = i

def build_bar(data: Any) -> Bar:
    return Bar(i=data["bar_i"])

@dataclass
class Foo:
    bar: Mapping[str, Bar] = field(default_factory=lambda: {})

dacite.from_dict(
    data_class=Foo,
    data={"bar": {"instance": {"bar_i": 1}}},
    config=dacite.Config(type_hooks={Bar: build_bar})
)