File tree 2 files changed +23
-8
lines changed
2 files changed +23
-8
lines changed Original file line number Diff line number Diff line change 1
1
import textwrap
2
- from typing import ClassVar
2
+ from typing import Any , ClassVar
3
3
4
+ import numpy as np
4
5
import yaml
5
- from pydantic import BaseModel
6
+ from asdf .tags .core import NDArrayType
7
+ from numpy .typing import NDArray
8
+ from pydantic import BaseModel , ValidationInfo , field_validator
6
9
7
10
8
11
class AsdfPydanticModel (BaseModel ):
@@ -67,3 +70,14 @@ def schema_asdf(
67
70
)
68
71
body = yaml .dump (cls .schema ())
69
72
return header + body
73
+
74
+ @field_validator ("*" , mode = "before" )
75
+ @classmethod
76
+ def _allow_asdf_NDArrayType_to_be_ndarray (
77
+ cls , value : Any , info : ValidationInfo
78
+ ) -> Any | NDArray :
79
+ """Before Pydantic validation, convert NDArrayType to ndarray."""
80
+ if not isinstance (value , NDArrayType ):
81
+ return value
82
+
83
+ return np .asarray (value )
Original file line number Diff line number Diff line change @@ -37,12 +37,13 @@ def test_convert_ArrayContainer_to_asdf(tmp_path):
37
37
"""When writing ArrayContainer to an ASDF file, the array field should be
38
38
serialized to the original numpy array.
39
39
"""
40
- af = asdf . AsdfFile ({ "data" : ArrayContainer (array = np .array ([1 , 2 , 3 ]))}). write_to (
41
- tmp_path / "test. asdf"
42
- )
40
+ data = ArrayContainer (array = np .array ([1 , 2 , 3 ]))
41
+ af = asdf . AsdfFile ({ "data" : data })
42
+ af . write_to ( tmp_path / "test.asdf" )
43
43
44
44
with asdf .open (tmp_path / "test.asdf" ) as af :
45
- assert isinstance (af .tree ["array" ], np .ndarray ), (
46
- f"Expected { type (np .ndarray )} , " f"got { type (af .tree ['array' ])} "
45
+ breakpoint ()
46
+ assert isinstance (af .tree ["data" ], np .ndarray ), (
47
+ f"Expected { type (np .ndarray )} , " f"got { type (af .tree ['data' ])} "
47
48
)
48
- assert np .all (af .tree ["array " ] == np .array ([1 , 2 , 3 ]))
49
+ assert np .all (af .tree ["data " ] == np .array ([1 , 2 , 3 ]))
You can’t perform that action at this time.
0 commit comments