If you need also the type of each field you might just use jsonref
:
import jsonref
from pprint import pprint
from enum import Enum
class Values(Enum):
a = 'a'
b = 'b'
class Mdl(BaseModel):
par: Values = Field(
title="par",
description="description of my parameter"
)
par2: str = Field(
title="par2",
description="description of my parameter"
)
par3: int = Field(
title="par3",
description="description of my parameter"
)
class Config:
""" Automatically convert enum to values """
use_enum_values = True
pprint(jsonref.loads(Mdl.schema_json()))
produces
{'definitions': {'Values': {'description': 'An enumeration.',
'enum': ['a', 'b'],
'title': 'Values'}},
'properties': {'par': {'allOf': [{'title': 'Values', 'description': 'An enumeration.', 'enum': ['a', 'b']}],
'description': 'description of my parameter',
'title': 'MyParameter'},
'par2': {'description': 'description of my parameter',
'title': 'MyParameter',
'type': 'string'},
'par3': {'description': 'description of my parameter',
'title': 'MyParameter',
'type': 'integer'}},
'required': ['par', 'par2', 'par3'],
'title': 'Mdl',
'type': 'object'}
Latter might further cleaned with
sch = jsonref.loads(Mdl.schema_json())
for par in sch['properties']:
if 'allOf' in sch['properties']['par']:
if 'enum' in sch['properties']['par']['allOf'][0]:
sch['properties']['par']['title'] = sch['properties']['par']['allOf'][0]['title']
sch['properties']['par']['allowed_values'] = sch['properties']['par']['allOf'][0]['enum']
sch['properties']['par'].pop('allOf')
that returns
{'definitions': {'Values': {'description': 'An enumeration.',
'enum': ['a', 'b'],
'title': 'Values'}},
'properties': {'par': {'allowed_values': ['a', 'b'],
'description': 'description of my parameter',
'title': 'Values'},
'par2': {'description': 'description of my parameter',
'title': 'MyParameter',
'type': 'string'},
'par3': {'description': 'description of my parameter',
'minimum': 0,
'title': 'MyParameter',
'type': 'integer'}},
'required': ['par', 'par2', 'par3'],
'title': 'Mdl',
'type': 'object'}
__post_init__
or__init__
- but pydantic seems to have a mind of its own – Riding