File tree Expand file tree Collapse file tree 2 files changed +32
-1
lines changed Expand file tree Collapse file tree 2 files changed +32
-1
lines changed Original file line number Diff line number Diff line change @@ -32,7 +32,15 @@ def create_instance(raw_data, validator):
3232 return raw_data
3333 return validator (raw_data ) # just return a list
3434
35- return core_schema .no_info_wrap_validator_function (function = create_instance , schema = list_schema )
35+ return core_schema .no_info_wrap_validator_function (
36+ function = create_instance ,
37+ schema = list_schema ,
38+ serialization = core_schema .plain_serializer_function_ser_schema (
39+ lambda val : list (v for v in val ),
40+ return_schema = list_schema ,
41+ when_used = "json" ,
42+ ),
43+ )
3644
3745
3846class CspTypingUtils39 :
Original file line number Diff line number Diff line change @@ -33,6 +33,7 @@ class StructNoDefaults(csp.Struct):
3333 a2 : List [str ]
3434 a3 : FastList [object ]
3535 a4 : List [bytes ]
36+ a5 : Numpy1DArray [float ]
3637
3738
3839class StructWithDefaults (csp .Struct ):
@@ -830,6 +831,28 @@ def test_from_dict_loop_with_defaults(self):
830831 del comp .np_arr
831832 self .assertEqual (looped , comp )
832833
834+ def test_to_json_loop_with_no_defaults (self ):
835+ for use_pydantic in [True , False ]:
836+ base_struct = StructNoDefaults (
837+ a1 = [9 , 10 ],
838+ a5 = np .array ([1 , 2 , 3 ]),
839+ bt = b"ab\001 \000 c" ,
840+ )
841+ if not use_pydantic :
842+ # Need the callback to handle the numpy array type
843+ looped = StructNoDefaults .type_adapter ().validate_json (base_struct .to_json (lambda x : x .tolist ()))
844+ else :
845+ looped = StructNoDefaults .type_adapter ().validate_json (
846+ StructNoDefaults .type_adapter ().dump_json (base_struct )
847+ )
848+ # Note that we cant compare numpy arrays, so we check them independently
849+ self .assertTrue (np .array_equal (looped .a5 , base_struct .a5 ))
850+
851+ del looped .a5
852+ del base_struct .a5
853+ self .assertEqual (looped , base_struct )
854+ self .assertFalse (isinstance (looped .a1 , list ))
855+
833856 def test_from_dict_loop_with_generic_typing (self ):
834857 class MyStruct (csp .Struct ):
835858 foo : Set [int ]
You can’t perform that action at this time.
0 commit comments