konradhalas / dacite

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

support for dashes in dictionary keys? #90

Closed muxator closed 4 years ago

muxator commented 4 years ago

Hi,

I am trying to convert a legacy project's configuration structures from dictionaries to dataclasses. dacite is a wonderful library for accomplishing this.

I have a problem that probably is going to be common enough, and I wanted to know if dacite supports this case.

In my project the incoming dictionary's structure has to be considered fixed, for backwards compatibility reasons. Unfortunately, some keys of that dictionary contain a dash (for example: is-active instead of is_active like in dacite's main the example).

I would be ok with changing the name of the dataclass member, replacing the dash with something else, but I cannot change the structure of the incoming dictionary. Something on the lines of:

from dataclasses import dataclass
from dacite import from_dict

@dataclass
class User:
    name: str
    age: int

    # - a "magical" auto conversion of "-" to "_" (bad)?
    # - a an explicit mapping of the source key name via some annotation?
    is_active: bool # <-- just a proposal

data = {
    'name': 'John',
    'age': 30,
    'is-active': True,   # <-- dict key name has a dash, and cannot be changed
}

user = from_dict(data_class=User, data=data)

assert user == User(name='John', age=30, is_active=True)

Does dacite currently support this use case?

Thanks

konradhalas commented 4 years ago

Hi @muxator - thank you, glad that dacite is helpful :)

We had the feature you are looking for in pre 1.x versions - it was called remap, but after some discussions (#38) I decided to remove all dict shape transformation features (#52).

So current approach is that you should call your own shape/field names transformation function before you pass data to dacite:

dacite.from_dict(data_class=User, data=transform_to_snake_case(data))

So you have to implement transform_to_snake_case on your own or try to find something on PyPI.

muxator commented 4 years ago

Hi @konradhalas, thanks for the help.

That's a good design decision, it makes perfect sense. I'll go on with the approach you suggested, and I will try to read the documentation with the eyes of a newbye. Who knows we can find a way to make it evident in the docs.

Thanks again!