toumorokoshi / jsonschema-extractor

Extract jsonschema from various Python objects
MIT License
26 stars 9 forks source link

It doesn't represent nested classes that are optional #16

Open MicaelJarniac opened 1 year ago

MicaelJarniac commented 1 year ago
import attrs
from jsonschema_extractor import extract
from pydantic import BaseModel

@attrs.define
class AttrsInner:
    a: int
    b: list[float]

@attrs.define
class AttrsOuter:
    inner: AttrsInner | None = None
    c: str = "foo"

class PyInner(BaseModel):
    a: int
    b: list[float]

class PyOuter(BaseModel):
    inner: PyInner | None = None
    c: str = "foo"

print(f"{extract(AttrsOuter) = }")
print()
print(f"{PyOuter.schema_json() = }")
extract(AttrsOuter) = {'title': 'AttrsOuter', 'type': 'object', 'properties': {'inner': {'type': 'object'}, 'c': {'type': 'string'}}, 'required': []}

PyOuter.schema_json() = '{"title": "PyOuter", "type": "object", "properties": {"inner": {"$ref": "#/definitions/PyInner"}, "c": {"title": "C", "default": "foo", "type": "string"}}, "definitions": {"PyInner": {"title": "PyInner", "type": "object", "properties": {"a": {"title": "A", "type": "integer"}, "b": {"title": "B", "type": "array", "items": {"type": "number"}}}, "required": ["a", "b"]}}}'
toumorokoshi commented 1 year ago

Hello! I'll try to take a look, but it might be a while.

Feel free to send a PR to fix if you can find the root cause: nested extractors should generally work as sub-types are still passed back to the general extractor