s-knibbs / dataclasses-jsonschema

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

Support for subclass type specialization #108

Closed jameskeane closed 4 years ago

jameskeane commented 4 years ago

Some guidance on whether this is a good or bad idea, but I'd like to do something like this:

@dataclass
class BaseObject(JsonSchemaMixin):
    field: str

@dataclass
class NarrowedObject(BaseMessage, JsonSchemaMixin):
    field: Literal['staticstr']

I've got a very simple patch to do this, a very small change to _get_fields_uncached that checks not only the base field name, but also it's type. I'm happy to contribute, unless there is a reason not to do this.

s-knibbs commented 4 years ago

Yeah, it looks like this is relatively simple to fix. I'm happy for you to contribute a fix for this.

If you don't need to serialise the base object, you can work around this for now by not adding JsonSchemaMixin to the base class.

In the above example, I'd guess this should generate the following schema:

{
  "allOf": [
    {
      "$ref": "#/definitions/BaseMessage"
    },
    {
      "type": "object",
      "properties": {
        "field": {
          "type": "string",
          "enum": ["staticstr"]
        }
      }
    }
  ],
  "description": "NarrowedObject(field: typing_extensions.Literal['test'])",
  "$schema": "http://json-schema.org/draft-06/schema#",
  "definitions": {
    "BaseMessage": {
      "type": "object",
      "required": [
        "field"
      ],
      "properties": {
        "field": {
          "type": "string"
        }
      },
      "description": "BaseMessage(field: str)"
    }
  }
}