konradhalas / dacite

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

Should it work with Dict[sometype, sometype]? #247

Open belonesox opened 1 year ago

belonesox commented 1 year ago

Consider a sample:

import dataclasses as dc
import dacite
from typing import List, Dict

@dc.dataclass
class TestProfileSpec:
    distro:   str = ''
    setup:    str = ''

class TestProfiles(Dict[str, TestProfileSpec]):
    ...

@dc.dataclass
class TestsSpec:
    profiles: TestProfiles = dc.field(default_factory=TestProfiles)

adict = {'profiles': 
            {'debian': 
                {'distro': 'debian:12', 
                 'setup': 'sudo apt-get install firefox-esr -y'
                }
            }, 
}    

parsed_ = dacite.from_dict(
        data_class=TestsSpec, 
        data=adict, 
        config=dacite.Config(cast=[TestProfiles, TestProfileSpec]))

print(type(parsed_))  # OK → <class '__main__.TestsSpec'>
print(type(parsed_.profiles)) # OK → <class '__main__.TestProfiles'>

print(type(parsed_.profiles['debian'])) # Not OK, → <class 'dict'> , wanted TestProfileSpec

See last line, I want to get TestProfileSpec type, but get standard dict.

I am not sure, if it bug or feature (I have not see any examples of dacite with «typed Dicts»), but I want any idea how to get it working (to get right class in last line).