Skip to content

Commit

Permalink
Merge pull request #119 from Suraj3620/pydantic-to-schemas
Browse files Browse the repository at this point in the history
Added helper function to convert pydantic model to schema
  • Loading branch information
dokempf authored Jan 21, 2025
2 parents f0e51fe + 26872d9 commit 7ee2236
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
11 changes: 11 additions & 0 deletions ipywidgets_jsonschema/form.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import re
import traitlets
import collections.abc
from pydantic import BaseModel

# We are providing some compatibility for ipywidgets v7 and v8
IS_VERSION_8 = version.parse(ipywidgets.__version__).major == 8
Expand Down Expand Up @@ -41,6 +42,15 @@ def as_tuple(obj):
return (obj,)


def convert_pydantic_to_schema(model) -> dict:
"""
Converts a Pydantic model class to its corresponding JSON schema.
"""
if isinstance(model, type) and issubclass(model, BaseModel):
return model.model_json_schema()
return model


def minmax_schema_rule(widget, schema):
"""This implements the minimum/maximum rules
Expand Down Expand Up @@ -115,6 +125,7 @@ def __init__(
A function that is used to sort the keys in a dictionary. Defaults to
the built-in sorted, but is no-op if sorted raises a TypeError.
"""
schema = convert_pydantic_to_schema(schema)
# Make sure that the given schema is valid
Draft7Validator.check_schema(schema)

Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ dependencies = [
"jsonschema<5",
"packaging",
"traitlets",
"pydantic",
]

[tool.setuptools]
Expand Down

0 comments on commit 7ee2236

Please sign in to comment.