Skip to content

Commit fed3c4b

Browse files
committed
Fix issue with serializing numpy ndarrays
Attributes that contain numpy nd arrays will be serialized to lists by default.
1 parent a061d40 commit fed3c4b

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/modelspec/base_types.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -837,6 +837,9 @@ def _is_list_base(cl):
837837
_base_struct_hook_factory,
838838
)
839839

840+
# Add a general hook for handling ndarray unstructure
841+
converter.register_unstructure_hook(np.ndarray, _unstructure_value_expr)
842+
840843
# Define some aliases for attr.define and other attrs stuff. This should hid attrs from the user a bit.
841844
define = attr.define
842845
has = attr.has

tests/test_base.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from modelspec import field, instance_of, optional, Base
55
from modelspec.base_types import value_expr_types, ValueExprType, print_v
66

7-
from typing import List, Dict, Any
7+
from typing import List, Dict, Any, Optional
88

99
import sys
1010

@@ -298,3 +298,17 @@ class Document(Base):
298298
doc.to_yaml()
299299
doc.generate_documentation(format="markdown")
300300
doc.generate_documentation(format="rst")
301+
302+
303+
def test_ndarray_json_metadata():
304+
import numpy as np
305+
306+
@modelspec.define(eq=False)
307+
class Node(Base):
308+
id: str = field(validator=instance_of(str))
309+
metadata: Optional[Dict[str, Any]] = field(
310+
kw_only=True, default=None, validator=optional(instance_of(dict))
311+
)
312+
313+
model = Node(id="a", metadata={"b": np.array([0])})
314+
model.to_json()

0 commit comments

Comments
 (0)