Dydantic
Dydantic is a Python library designed for dynamically generating Pydantic models directly from JSON Schema definitions. It offers a streamlined approach to creating Pydantic models on-the-fly, based on user-defined schemas, and is currently at version 0.0.8. The project appears to be actively maintained, with a recent PyPI release and GitHub activity.
Warnings
- breaking Dydantic requires Pydantic v2.x. Users migrating from Pydantic v1.x projects will encounter breaking changes in Pydantic's API (e.g., method renames like `dict()` to `model_dump()`, `json()` to `model_dump_json()`, and changes to configuration handling).
- gotcha Pydantic v2, which Dydantic leverages, has stricter type coercion rules. Data that might have been implicitly coerced in Pydantic v1 (e.g., a number string to an integer) may now raise validation errors if the JSON schema type doesn't perfectly match the input data.
- gotcha In Pydantic v2 (and thus Dydantic-generated models), a field annotated as `typing.Optional[T]` is considered required by default and merely *allows* a value of `None`. It does not automatically provide a default value of `None`. If your JSON schema implies optionality via `nullable: true` but doesn't provide a `default` value, the field will still be required unless an explicit Python `default=None` is passed during model creation or the field is marked as not required.
Install
-
pip install -U dydantic
Imports
- create_model_from_schema
from dydantic import create_model_from_schema
Quickstart
from dydantic import create_model_from_schema
json_schema = {
"title": "Person",
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
},
"required": ["name"]
}
Person = create_model_from_schema(json_schema)
person_instance = Person(name="Jane Doe", age=30)
print(person_instance.model_dump_json(indent=2))
# Expected output:
# {
# "name": "Jane Doe",
# "age": 30
# }