Better support for types outside of the standard library
See original GitHub issueI have had a bit of a problem with dacite’s way of handling type conversions from str
to Enum
. In pre 1.0 I had to use cast
to be able use Enum
’s in a dataclass
. For example:
from dataclasses import dataclass
from enum import Enum
import dacite
class Thing(Enum):
Foo = "foo"
Bar = "bar"
@dataclass
class Container:
simple: str
thing: Thing
data = {
"simple": "value",
"thing": "foo"
}
container = dacite.from_dict(data_class=Container, data=data, config=dacite.Config(cast=["thing"]))
It seems that 1.0 removes a lot of functionality, but I can still work with enums by using the type_hooks
-feature in the Config
.
container = dacite.from_dict(data_class=Container, data=data, config=dacite.Config(type_hooks={Thing: Thing}))
I am not sure how dacite
is used but it seems to me that as a user of the library, my expectation is that types are automatically converted according to the definition of the dataclass that is passed to from_dict()
. Attempting to automatically transform the types in the case of non-standard-library types would follow the principle of least astonishment and I do not think it is hard to implement.
For example it might be possible to populate a default type_hooks
in from_dict
, and then update it based on the configuration provided by the user. The user is still able to pass custom transformations so the change should be backwards compatible with 1.0. A very, very crude example
# In this example,data_class is the Container from my example
default = {f.type: f.type for f in dataclasses.fields(data_class)}
default.update(config.type_hooks)
updated_hooks = default
try:
field_data = data[field.name]
transformed_value = transform_value(
type_hooks=updated_hooks, target_type=field.type, value=field_data
)
value = _build_value(type_=field.type, data=transformed_value, config=config)
except DaciteFieldError as error:
error.update_path(field.name)
raise
@konradhalas I might be open to contributing such functionality in a PR if you’re not against the idea and if you’re willing to provide some idea as a maintainer of how you’d like that implementation to look like.
Issue Analytics
- State:
- Created 4 years ago
- Comments:8 (4 by maintainers)
Top GitHub Comments
@mvalkon your welcome 😃 I’m happy that you found the root cause. I will think about
cast
feature, but for now, if you don’t mind, I close this issue.@konradhalas Thank you very much for your explanation! The current solution works for me and
Config.cast_all
feels like a great addition.