konradhalas / dacite

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

Feature request: Convert strings to UUID #18

Closed condemil closed 5 years ago

condemil commented 5 years ago

I want to use dacite to map json that is returned from http call to dataclass. As soon as there is no UUID type in json the received uuid have string type. Instead of manually converting all UUIDs before calling from_dict() it will be really nice if dacite can check that input type is string and required type is UUID and convert string to UUID in background.

konradhalas commented 5 years ago

Hi @condemil thank you for your issue :)

Did you try with Config.transformation or Config.cast?

konradhalas commented 5 years ago

Here you go:

from dataclasses import dataclass
from uuid import UUID

import dacite

@dataclass
class X:
    id: UUID

data = {
    'id': '715d2862-cae0-4d61-8491-a6aa2311e859',
}

x = dacite.from_dict(
    data_class=X,
    data=data,
    config=dacite.Config(cast=['id']),
)

Is it what you are looking for? :)

condemil commented 5 years ago

Thank you for providing an example and giving a solution, I missed that I can use dacite.Config(cast=['id']). As soon as it works this way I am gonna close the feature request.

konradhalas commented 5 years ago

@condemil good to hear.

Maybe it's a good idea to add cast_all flag to Config. In this case, dacite should try to cast value, but only if a "raw" value from data dict is not an instance of given field type. I will think about it.