konradhalas / dacite

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

identifier aliases #194

Closed chebureki closed 1 year ago

chebureki commented 1 year ago

How would one create a data class from a dict, with indexes which can't be python identifiers? I'm not too familiar with python, but I didn't seem to find a way to escape an identifier. e.g.:

@dataclass
class SomeData:
 foo: int # cant call it $foo :-(
 bar: int

some_data_dict = {
 "$foo" : 1,
 "bar": 2,
} 

How about a identifier mapping? Kinda hacky, but should do the job. e.g.:

data = from_dict(X, SomeData, Config(identifier_mapping={"$foo": "foo"}))

Or is it better to let the user rename the dict indexes himself?

hemna commented 1 year ago

I have a similar case where the key in the dictionary is a python reserved keyword "from"


@dataclass
class Packet:
  from_call: str
  to_call: str

data_packet = {
    "from": "my friend"
    "to": "to me"
}

Is there a way to have the "from" key in the dict set in the class as the "from_call" var?
konradhalas commented 1 year ago

@chebureki thank you for reporting this issue but I don't think we should add such config to this library (TBH we had such feature long time ago but I removed it). You can always clean up your data on your own before you pass them to from_dict function.