Discriminator and recursive fields
gsakkis opened this issue · comments
I'm trying to define a recursive type with a discriminator as follows:
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Annotated
import apischema
@dataclass
class FileApi:
name: str
@dataclass
class DirectoryApi:
name: str
contents: list[FileApi | DirectoryApi] = field(default_factory=list)
NodeApi = Annotated[
DirectoryApi | FileApi ,
apischema.discriminator("type", {"file": FileApi, "directory": DirectoryApi})
]
print(apischema.deserialize(NodeApi, {"type": "file", "name": "foo.txt"}))
print(apischema.deserialize(NodeApi, {"type": "directory", "name": "images"}))
The first print succeeds (FileApi(name='foo.txt')
) but the second fails with
apischema.validation.errors.ValidationError: ValidationError: [{'loc': ['type'], 'err': 'unexpected property'}]
What's the right way to make this work?
Hi, thank you for opening this issue.
I've started to investigate, and I've found that if you remove the fields contents: list[FileApi | DirectoryApi]
, it works. So this is definitely a bug, and I will investigate further.
I've isolated the bug and fixed it. I will push the PR soon.