Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

All pending dacite PRs - merged and released as dacite2 #1

Merged
merged 19 commits into from
Dec 5, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
from_dict customization per data class
trojkat authored and idanmiara committed Nov 30, 2022
commit e7adcc99d1e948e53965d51ee30e337de110c95c
2 changes: 2 additions & 0 deletions dacite/core.py
Original file line number Diff line number Diff line change
@@ -98,6 +98,8 @@ def _build_value(type_: Type, data: Any, config: Config) -> Any:
_build_value(type_=extract_generic(type_)[0], data=single_val, config=config) for single_val in data
)
elif is_dataclass(type_) and is_instance(data, Data):
if hasattr(type_, "from_dict"):
return type_.from_dict(data=data, config=config)
return from_dict(data_class=type_, data=data, config=config)
return data

33 changes: 33 additions & 0 deletions tests/core/test_config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from dataclasses import dataclass
from datetime import date
from enum import Enum
from typing import Optional, List, Union

@@ -224,3 +225,35 @@ class X:
b: str

assert X(a=1, b=None) == from_dict(X, {"a": 1}, Config(allow_missing_fields_as_none=True))


def test_custom_from_dict_in_nested_data_class():
@dataclass
class X:
d: date
t: str

def from_dict(data_class, data, config):
data["t"] = "prefix {}".format(data["t"])
return from_dict(
data_class=data_class,
data=data,
config=Config(type_hooks={date: date.fromtimestamp}),
)

@dataclass
class Y:
d: date
x: X

config = Config(type_hooks={date: date.fromordinal})
data = {"d": 737790, "x": {"d": 1607511900.985121, "t": "abc"}}
result = from_dict(Y, data, config=config)

assert result == Y(
d=date(2020, 12, 31),
x=X(
d=date(2020, 12, 9),
t="prefix abc",
),
)