konradhalas / dacite

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

Feature request: Convert strings to Enum #19

Closed condemil closed 5 years ago

condemil commented 5 years ago

When you have field with enum.Enum type it is not possible to parse json string and map it to dataclass. It will be nice to be able to convert string to enum field in background.

konradhalas commented 5 years ago

Simple example:

from dataclasses import dataclass
from enum import Enum

import dacite

class E(Enum):
    A = 1
    B = 2

@dataclass
class X:
    e: E

data = {
    'e': 1,
}

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

Does it solve your problem?

condemil commented 5 years ago

Yes, it solved my problem.

I was also using auto values and had enum keys in json, like

class E(Enum):
    A = auto()
    B = auto()

data = {
    'e': 'A',
}

but as a solution I am not using auto() and specified the same values as the keys.

So I am gonna close the feature request as soon as the provided solution fits my needs.

Garrett-R commented 3 years ago

For anyone else finding their way here, the above snippet didn't work for me, but reading the docs, this updated snippet works:

from dataclasses import dataclass
from enum import Enum

import dacite

class E(Enum):
    A = 1
    B = 2

@dataclass
class X:
    e: E

data = {
    'e': 1,
}

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