Skip to content
New issue

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

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

Already on GitHub? # to your account

Adding a special case for floats that are passed the strings "nan" or "inf" #257

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 2 additions & 0 deletions dacite/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ def _build_value(type_: Type, data: Any, config: Config) -> Any:
data = _build_value_for_collection(collection=type_, data=data, config=config)
elif cache(is_dataclass)(type_) and isinstance(data, Mapping):
data = from_dict(data_class=type_, data=data, config=config)
elif type_ == float and isinstance(data, str) and data.lower() in ["nan", "inf"]:
return type_(data)
for cast_type in config.cast:
if is_subclass(type_, cast_type):
if is_generic_collection(type_):
Expand Down
2 changes: 2 additions & 0 deletions dacite/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ def is_instance(value: Any, type_: Type) -> bool:
# As described in PEP 484 - section: "The numeric tower"
if (type_ in [float, complex] and isinstance(value, (int, float))) or isinstance(value, type_):
return True
if type_ == float and isinstance(value, str) and value.lower() in ["nan", "inf"]:
return True
except TypeError:
pass
if type_ == Any:
Expand Down
16 changes: 16 additions & 0 deletions tests/core/test_base.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import math
from dataclasses import dataclass, field
from typing import Any, NewType, Optional, List

Expand Down Expand Up @@ -204,3 +205,18 @@ class A:
a2 = from_dict(A, {"name": "a2"})

assert a1.items is not a2.items


def test_translate_nan_to_float():
@dataclass
class X:
i: float
n: float

result_1 = from_dict(X, {"i": "inf", "n": "nan"})
result_2 = from_dict(X, {"i": "INF", "n": "NaN"})

assert math.isnan(result_1.n)
assert math.isnan(result_2.n)
assert math.isinf(result_1.i)
assert math.isinf(result_2.i)