s-knibbs / dataclasses-jsonschema

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

Pipe | as alternative of Union is not working properly #195

Open visko-sc opened 1 year ago

visko-sc commented 1 year ago
from dataclasses import dataclass

from dataclasses_jsonschema import JsonSchemaMixin

@dataclass
class Numbers(JsonSchemaMixin):
    roman: str

@dataclass
class Math(JsonSchemaMixin):
    numbers: Numbers | None = None

print(Math(Numbers('X')).to_dict())

Actual result: {'numbers': Numbers(roman='X')}

Expected result: {'numbers': {'roman': 'X'}}

I think the problem can be fixed in either _get_field_type_name or in https://github.com/s-knibbs/dataclasses-jsonschema/blob/648ada22bf0cb9f19b0ed12e1870844d854015b5/dataclasses_jsonschema/__init__.py#L391

Note: These work as expected:

@dataclass
class Math2(JsonSchemaMixin):
    numbers: Union[Numbers, None] = None

@dataclass
class Math3(JsonSchemaMixin):
    numbers: Optional[Numbers] = None
ZdenekM commented 1 year ago

Duplicate of https://github.com/s-knibbs/dataclasses-jsonschema/issues/187?

visko-sc commented 1 year ago

They are related. But while #187 brings a specific problem (str | None) and schema creation, this is about the pipe operator and data class creation error. The root cause is probably the same.

s-knibbs commented 1 year ago

Adding from __future__ import annotations at the top fixed the example code you posted.