From 7fb9813ba0bbdf6510958bd29c802187baaf6e44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexandre=20Ren=C3=A9?= Date: Mon, 4 Sep 2023 12:28:24 +0200 Subject: [PATCH] Add fallback to `base_encoder` when serializing functions Things like callable Pydantic models may not be serializable with the function serializer but still serializable with the base encoder. --- scityping/json.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/scityping/json.py b/scityping/json.py index 00c7cfc..c3881b1 100644 --- a/scityping/json.py +++ b/scityping/json.py @@ -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: