From 08bcfecc4cc760d29db21bbdca3066b64af54012 Mon Sep 17 00:00:00 2001 From: Jacob Hayes Date: Sun, 1 Oct 2023 17:38:50 -0400 Subject: [PATCH] Fix user-defined model serialization Signed-off-by: Jacob Hayes --- src/hera/shared/_pydantic.py | 1 + src/hera/shared/serialization.py | 12 ++++++++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/hera/shared/_pydantic.py b/src/hera/shared/_pydantic.py index f5a5bba3d..f8251cf56 100644 --- a/src/hera/shared/_pydantic.py +++ b/src/hera/shared/_pydantic.py @@ -23,6 +23,7 @@ __all__ = [ "BaseModel", "Field", + "PydanticBaseModel", # Export for serialization.py to cover user-defined models "root_validator", "validate_arguments", "validator", diff --git a/src/hera/shared/serialization.py b/src/hera/shared/serialization.py index ca1e26b91..4314f6f7a 100644 --- a/src/hera/shared/serialization.py +++ b/src/hera/shared/serialization.py @@ -3,13 +3,17 @@ from json import JSONEncoder from typing import Any, Optional -from hera.shared._pydantic import BaseModel +# NOTE: Use the original BaseModel in order to support serializing user-defined models, +# which won't use our hera.shared._pydantic import. This does still require that the +# user-defined models are using v1 pydantic models for now (either from a pydantic v1 +# installation or `pydantic.v1` import from a pydantic v2 installation). +from hera.shared._pydantic import PydanticBaseModel MISSING = object() -"""`MISSING` is a placeholder that indicates field value nullity. +"""`MISSING` is a placeholder that indicates field value nullity. When the user of a Hera object sets the field of an object specifically to `None`, Hera needs to distinguish between -default nullity/None and user-provided `None` on, say, something like the `source` of `Script`. +default nullity/None and user-provided `None` on, say, something like the `source` of `Script`. """ @@ -18,7 +22,7 @@ class PydanticEncoder(JSONEncoder): def default(self, o: Any): """Return the default representation of the given object.""" - if isinstance(o, BaseModel): + if isinstance(o, PydanticBaseModel): return o.dict(by_alias=True) return super().default(o)