konradhalas / dacite

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

[question] How to use dacite when generating dictonary dynamically #193

Closed yozachar closed 1 year ago

yozachar commented 1 year ago

Here's a reproducible script:

from random import choice, randint
from dataclasses import dataclass

from dacite import from_dict

# please ignore the naming style, this is just a demo

@dataclass
class FITemp:
    """Form Inputs"""
    ip_t: str
    ip_n: str
    ip_v: str

@dataclass
class HFTemp:
    """Forms"""
    fm_n: str
    fm_m: str
    fm_a: str
    fm_f: tuple[FITemp]

sf = tuple(
    from_dict(
        data_class=HFTemp,
        data=dict({
            'fm_n': f'fm#{f_dx}',
            'fm_m': str(choice(('GET', 'POST'))),
            'fm_a': str(choice('ALPHABETS')),
            'fm_f': tuple(
                from_dict(
                    data_class=FITemp,
                    data=dict({
                        'ip_t': f'ip#{i_dx}',
                        'ip_n': str(choice(('date', 'color', 'textarea', 'range'))),
                        'ip_v': str(randint(0, 10)),
                    })
                ) for i_dx in range(5)
            ),
        })
    ) for f_dx in range(5)
)

print(sf)

But it errors out with:

Traceback (most recent call last):
  File "~/reproducer.py", line 29, in <module>
    sf = tuple(
  File "~/reproducer.py", line 30, in <genexpr>
    from_dict(
  File "~/.cache/pypoetry/virtualenvs/myVenv-py3.10/lib/python3.10/site-packages/dacite/core.py", line 68, in from_dict
    raise WrongTypeError(field_path=field.name, field_type=field.type, value=value)
dacite.exceptions.WrongTypeError: wrong value type for field "fm_f" - should be "tuple" instead of value "(FITemp(ip_t='ip#0', ip_n='color', ip_v='1'), FITemp(ip_t='ip#1', ip_n='color', ip_v='1'), FITemp(ip_t='ip#2', ip_n='date', ip_v='9'), FITemp(ip_t='ip#3', ip_n='date', ip_v='10'), FITemp(ip_t='ip#4', ip_n='date', ip_v='4'))" of type "tuple"

What am I missing?

konradhalas commented 1 year ago

@joe733 your typing is wrong, should be fm_f: tuple[FITemp, ...]