pythonserializationpython-dataclassespydantic-v2

Pydantic unknown type during serialization


I need to serialize a python dataclass (MainObj in the MWE below) which contains other plain-python nested objects, however the snippet below throws an exception.

mwe.py (entry point)

from mainobj import MAIN_OBJ_TA, MainObj
from myobj import MyObj, MyNestedObj

obj = MainObj(a=1, b="asd", c=MyObj(x=10, y="lol", z=MyNestedObj(100, "qwerty")))
j = MAIN_OBJ_TA.dump_json(obj)
print(j)

mainobj.py

from pydantic import TypeAdapter
from pydantic.dataclasses import dataclass

from myobj import MyObj

@dataclass(config={'arbitrary_types_allowed': True})
class MainObj:
    a: int
    b: str
    c: MyObj

MAIN_OBJ_TA = TypeAdapter(MainObj)

myobj.py

# from dataclasses import dataclass

# @dataclass
class MyNestedObj:
    h: int
    k: str

    def __init__(self, h, k):
        self.h = h
        self.k = k

# @dataclass
class MyObj:
    x: int
    y: str
    z: MyNestedObj

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

If I run python mwe.py at line j = MAIN_OBJ_TA.dump_json(obj) I get

pydantic_core._pydantic_core.PydanticSerializationError: Unable to serialize unknown type: <class 'myobj.MyObj'>

However, if I turn the python classes in myobj.py into python dataclasses (removing the comments), it works and I see

b'{"a":1,"b":"asd","c":{"x":10,"y":"lol","z":{"h":100,"k":"qwerty"}}}'

Is this the intended behaviour? I would like to be able to serialize the objects in myobj.py without turning them into dataclasses (as in my actual use case I have no control over them).


Solution

  • The question was answered in this related Github issue.