Skip to content
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
5 changes: 5 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
Changelog
=========

Version 7.4.2
-------------

* Fixing #264 ruamel.yaml ScalarFloat/ScalarInt kept as non-builtin types after from_yaml

Version 7.4.1
-------------

Expand Down
26 changes: 25 additions & 1 deletion box/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,30 @@ def _to_yaml(
raise BoxError(MISSING_PARSER_ERROR)



def _ruamel_to_builtin(obj):
"""Convert ruamel.yaml scalar types to plain Python builtins.

ScalarFloat/ScalarInt survive Box.to_dict() and break serializers
that only accept builtin float/int (issue #264).
"""
if isinstance(obj, dict):
return {k: _ruamel_to_builtin(v) for k, v in obj.items()}
if isinstance(obj, list):
return [_ruamel_to_builtin(v) for v in obj]
module = type(obj).__module__
if module.startswith("ruamel"):
if isinstance(obj, bool):
return bool(obj)
if isinstance(obj, int):
return int(obj)
if isinstance(obj, float):
return float(obj)
if isinstance(obj, str):
return str(obj)
return obj


def _from_yaml(
yaml_string: str | None = None,
filename: str | PathLike | None = None,
Expand Down Expand Up @@ -272,7 +296,7 @@ def _from_yaml(
raise BoxError(MISSING_PARSER_ERROR)
else:
raise BoxError("from_yaml requires a string or filename")
return data
return _ruamel_to_builtin(data)


def _to_toml(obj, filename: str | PathLike | None = None, encoding: str = "utf-8", errors: str = "strict"):
Expand Down
11 changes: 11 additions & 0 deletions test/test_box.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,17 @@ def test_from_yaml(self):
assert bx.key1 == "value1"
assert bx.Key_2 == Box()


def test_from_yaml_builtin_scalars(self):
bx = Box.from_yaml("Float: 0.1\nCount: 4\nFlag: true\n")
assert type(bx.Float) is float
assert type(bx.Count) is int
assert type(bx.Flag) is bool
dumped = bx.to_dict()
assert type(dumped["Float"]) is float
assert type(dumped["Count"]) is int
assert dumped["Float"] == 0.1

def test_bad_from_json(self):
with pytest.raises(BoxError):
Box.from_json()
Expand Down