Pydantic is a popular Python library used for building robust, scalable, and maintainable data models. It provides a simple and intuitive way to define data structures, validate data, and generate JSON schemas. One of the key features of Pydantic is its ability to specify titles for models and fields, which is useful for generating human-readable documentation and improving the overall user experience.
Currently, Pydantic allows specifying a string literal for the title value used in the exported JSON schema. For BaseModel
, this can be accomplished via the Config
class:
from pydantic import BaseModel
class MyDataClass(BaseModel):
class Config:
title = "My Data Class"
Similarly, for BaseModel
fields, an explicit title string can be specified with a Field
instance:
from pydantic import BaseModel, Field
from typing import List
class MyDataClass(BaseModel):
matchCriteria: List[str] = Field(default_factory=list, title="Match Criteria")
class Config:
title = "My Data Class"
To enhance Pydantic's title specification functionality, we propose introducing a title_generator
class attribute in the Config
class and a title_generator
parameter in the Field
constructor. This would allow developers to specify a Python callable that generates the title value programmatically.
The title_generator
callable would take the BaseModel
class name or field alias as an argument, enabling developers to create custom title generation logic. For example:
import re
from pydantic import BaseModel
def make_title(name: str):
def _capitalize(v: str):
return v[0].upper() + v[1:]
return re.sub(r"(?<=[a-z])([A-Z])", r" \1", _capitalize(name))
class MyDataClass(BaseModel):
matchCriteria: List[str] = Field(default_factory=list, title_generator=make_title)
class Config:
title_generator = make_title
This would result in a JSON schema with programmatically generated titles:
{
"title": "My Data Class",
"type": "object",
"properties": {
"matchCriteria": {
"title": "Match Criteria",
"type": "array",
"items": {
"type": "string"
}
}
}
}
The proposed solution offers several benefits, including:
Adding a title_generator
class attribute and parameter to Pydantic's Config
class and Field
constructor, respectively, would provide a powerful and flexible way to specify titles for models and fields. This enhancement would improve the overall user experience, reduce maintenance efforts, and increase the readability of JSON schemas and documentation. Learn more about Pydantic and its features. For more information on JSON schema generation, visit the official JSON schema website.