Skip to content
Merged
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
22 changes: 22 additions & 0 deletions tests/test_hybrid_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,28 @@ class A(xo.HybridClass):
assert b_dict == {}


def test_to_dict_scalar_raw_union_defaults():
class ScalarUnion(xo.RawUnion):
scalar = xo.Float64
bits = xo.UInt64

@classmethod
def _from_buffer(cls, buffer, offset=0, container=None):
return xo.Float64._from_buffer(buffer, offset)

class A(xo.HybridClass):
_xofields = {
"a": ScalarUnion,
"b": xo.Field(ScalarUnion, default=2.5),
"c": xo.Field(ScalarUnion, default_factory=lambda: 3.5),
}

assert A().to_dict() == {"__class__": "A"}
values = {"__class__": "A", "a": 1.5, "b": 0.0, "c": 0.0}
for copy_to_cpu in (True, False):
assert A.from_dict(values).to_dict(copy_to_cpu=copy_to_cpu) == values


def test_to_dict_python_vars():
class TD(xo.HybridClass):
_xofields = {
Expand Down
8 changes: 7 additions & 1 deletion xobjects/hybrid_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from .struct import Struct
from .typeutils import context_default
from .ref import Ref
from .raw_union import RawUnion


class _FieldOfDressed:
Expand Down Expand Up @@ -297,7 +298,12 @@ def to_dict(self, copy_to_cpu=True):
defaults[field.name] = dft
continue
try:
defaults[field.name] = field.get_default()
default = field.get_default()
if isinstance(default, RawUnion):
# A raw union can expose a scalar when read as a field.
default = type(default)._from_buffer(
default._buffer, default._offset)
defaults[field.name] = default
except (TypeError, ValueError):
# The above can fail with different error types
# if a field type is dynamic.
Expand Down
Loading