Skip to content

Commit

Permalink
feat: Field Name in builts-in support with _ in end
Browse files Browse the repository at this point in the history
  • Loading branch information
JCHacking committed Oct 12, 2023
1 parent 10a9ec4 commit 9036145
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

Nothing yet.
### Added
- Named field matches a built-in now works with the pep8 naming convention with _ at the end

## [1.8.1] - 2023-05-12

Expand Down
6 changes: 4 additions & 2 deletions dacite/core.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import builtins
from dataclasses import is_dataclass
from itertools import zip_longest
from typing import TypeVar, Type, Optional, get_type_hints, Mapping, Any, Collection, MutableMapping
Expand Down Expand Up @@ -57,10 +58,11 @@ def from_dict(data_class: Type[T], data: Data, config: Optional[Config] = None)
if extra_fields:
raise UnexpectedDataError(keys=extra_fields)
for field in data_class_fields:
data_name = field.name[:-1] if field.name.endswith("_") and field.name[:-1] in dir(builtins) else field.name
field_type = data_class_hints[field.name]
if field.name in data:
if data_name in data:
try:
field_data = data[field.name]
field_data = data[data_name]
value = _build_value(type_=field_type, data=field_data, config=config)
except DaciteFieldError as error:
error.update_path(field.name)
Expand Down
26 changes: 26 additions & 0 deletions tests/core/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,29 @@ class A:
a2 = from_dict(A, {"name": "a2"})

assert a1.items is not a2.items


def test_from_dict_with_built_in_field():
@dataclass
class X:
id: int
s: str
i: int
f: float

result = from_dict(X, {"id": 1, "s": "test", "i": 1, "f": 1.0})

assert result == X(id=1, s="test", i=1, f=1.0)


def test_from_dict_with_built_in_field_pep8():
@dataclass
class X:
id_: int
s: str
i: int
f: float

result = from_dict(X, {"id": 1, "s": "test", "i": 1, "f": 1.0})

assert result == X(id_=1, s="test", i=1, f=1.0)

0 comments on commit 9036145

Please sign in to comment.