From 90361457d427e1f6fe23c1bcb585e5fcb12e9adb Mon Sep 17 00:00:00 2001 From: JCHacking Date: Thu, 12 Oct 2023 19:19:49 +0200 Subject: [PATCH] feat: Field Name in builts-in support with _ in end --- CHANGELOG.md | 3 ++- dacite/core.py | 6 ++++-- tests/core/test_base.py | 26 ++++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f06914f..63aeadc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/dacite/core.py b/dacite/core.py index 9e45129..d82f22f 100644 --- a/dacite/core.py +++ b/dacite/core.py @@ -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 @@ -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) diff --git a/tests/core/test_base.py b/tests/core/test_base.py index a866d57..f8c69d2 100644 --- a/tests/core/test_base.py +++ b/tests/core/test_base.py @@ -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)