s-knibbs / dataclasses-jsonschema

JSON schema generation from dataclasses
MIT License
166 stars 38 forks source link

Missing definition in schema with Optional[Union[A,B]] #147

Closed jobh closed 3 years ago

jobh commented 3 years ago

Definitions are missing for some references when using Optional[Union[A,B]] of nested classes. The same problem appears when adding None to the union instead of making it Optional.

Test case below.

from dataclasses import dataclass
from dataclasses_jsonschema import JsonSchemaMixin
from typing import Optional, Union
import json

@dataclass
class A(JsonSchemaMixin):
    a: str

@dataclass
class B(JsonSchemaMixin):
    b: str

@dataclass
class C(JsonSchemaMixin):
    c: Union[A,B]

@dataclass
class D(JsonSchemaMixin):
    d: Optional[Union[A,B]]

print(C.json_schema()['definitions'].keys())
print(D.json_schema()['definitions'].keys())

Output (the two lines should be equal):

dict_keys(['A', 'B'])
dict_keys(['A'])