Skip to content

Commit

Permalink
Add fallback to base_encoder when serializing functions
Browse files Browse the repository at this point in the history
Things like callable Pydantic models may not be serializable with the
function serializer but still serializable with the base encoder.
  • Loading branch information
alcrene committed Sep 4, 2023
1 parent b66e3b6 commit 7fb9813
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion scityping/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,17 @@ def scityping_encoder(obj: Any, base_encoder=None) -> Any:
# used for packaging data, in particular for our nested Data classes
return Dataclass.deep_reduce(obj)
elif isinstance(obj, Callable): # NB: We don't want to do this within 'Data.encode', because sometimes we
return serialize_function(obj) # use 'encode' without going all the way to a JSON string
try:
return serialize_function(obj) # use 'encode' without going all the way to a JSON string
except TypeError as e:
# Things like callable Pydantic models may not be serializable with the function serializer,
# but still serializable with the base encoder.
# (NB: We don’t try the base encoder first, because we want to give
# the function serializer priority.)
if base_encoder:
return base_encoder(obj)
else:
raise e
elif base_encoder:
return base_encoder(obj)
else:
Expand Down

0 comments on commit 7fb9813

Please sign in to comment.