Convert Python types and typing annotations into a simple schema representation.
Project description
Typing schema
Convert Python types and typing annotations (including Annotated, Union, Literal, dataclasses, TypedDicts, and pydantic.BaseModel) into a simple schema representation.
Overview
This library provides utilities to transform Python type hints and function signatures into a JSON-like schema. It is useful for documenting or validating function inputs and the data structures described by Python typing constructs. It can also generate parameter schemas compatible with OpenAI's function-calling API, making it easier to provide accurate function parameter definitions for model function calls.
Key features:
- Convert basic types (
str,int,float,bool,list,dict) to simple value schemas. - Convert
Union,Literal,Enum,Annotated(with inline descriptions),dataclasses,TypedDict, andpydantic.BaseModelto object/oneOf/enum schemas. - Convert a function signature into a schema that lists parameters, types, and required fields.
- Provide extension points: custom type handlers and annotated-doc handlers.
Usage
Basic example using type annotations:
Convert a typing annotation
from schema_builder import typing_to_schema, function_to_schema
from typing import Annotated, Union, Literal
class Record(TypedDict):
"""The record item"""
id: int
name: str
content: Annotated[str | None, "The content (Optional)"]
schema = typing_to_schema(Record)
print(json.dumps(schema, indent=2))
Output:
{
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"content": {
"type": [
"string",
"null"
],
"description": "The content (Optional)"
}
},
"required": [
"id",
"name"
],
"description": "The record item"
}
Convert a function signature
def func(a: int, b: str = 'x') -> None:
"""Example function"""
pass
schema = function_to_schema(func)
print(json.dumps(schema, indent=2))
Output:
{
"type": "object",
"properties": {
"a": {
"type": "integer"
},
"b": {
"type": "string",
"default": "x"
}
},
"required": [
"a"
],
"description": "Example function"
}
Extension points
type_handler: pass a callback totyping_to_schemaorfunction_to_schemato handle custom types. If it returns a schema the converter will use it.annotated_doc_handler: pass a callback to extract documentation fromAnnotated[...]metadata.
Handle custom types
def handler(type) -> dict | None:
if (
type is datetime.datetime
or isinstance(type, datetime.date)
or issubclass(type, datetime.date)
):
return {"type": "string", "description": "Handled string type"}
return None
schema = typing_to_schema(datetime.date, type_handler=handler)
print(json.dumps(schema, indent=2))
Output:
{
"type": "string",
"description": "Handled string type"
}
Extract documentation from Annotated metadata
By default, the first str value in Annotated metadata is used as the description.
class Doc:
def __init__(self, value: str):
self.value = value
def doc_handler(args: tuple[type, ...]) -> str | None:
for arg in args:
if isinstance(arg, Doc):
return arg.value
return None
class Record(TypedDict):
name: Annotated[str, Doc("The name of the person")]
schema = typing_to_schema(Record, annotated_doc_handler=doc_handler)
print(json.dumps(schema, indent=2))
output:
{
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the person"
}
},
"required": [
"name"
]
}
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file typing_schema-0.1.0.tar.gz.
File metadata
- Download URL: typing_schema-0.1.0.tar.gz
- Upload date:
- Size: 7.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
936c680f9314f2d488d3c4dc69e3488e5bc7040fcd2f0ad54426fd708f38bbb0
|
|
| MD5 |
ed3fbef56bbe01f7b8702e9d30ab3525
|
|
| BLAKE2b-256 |
fbaa266fe03ec54db741f5623dcd80575b644de4528e6bea5b832fe20116887a
|
Provenance
The following attestation bundles were made for typing_schema-0.1.0.tar.gz:
Publisher:
python-publish.yml on kasancode/Typing-schema
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
typing_schema-0.1.0.tar.gz -
Subject digest:
936c680f9314f2d488d3c4dc69e3488e5bc7040fcd2f0ad54426fd708f38bbb0 - Sigstore transparency entry: 719594813
- Sigstore integration time:
-
Permalink:
kasancode/Typing-schema@6e3fe97947592820b17caffa641132822db1c670 -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/kasancode
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@6e3fe97947592820b17caffa641132822db1c670 -
Trigger Event:
release
-
Statement type:
File details
Details for the file typing_schema-0.1.0-py3-none-any.whl.
File metadata
- Download URL: typing_schema-0.1.0-py3-none-any.whl
- Upload date:
- Size: 6.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b1a0407104139246dd70f1abb0c6de38a5ca7b31824eab38376cae4a99d68881
|
|
| MD5 |
ac940200fd25af92de3805e08e9f1df6
|
|
| BLAKE2b-256 |
f53c110bd2f425f75b97a9715a615e37410471c68bf6b95518dcf65ef980baff
|
Provenance
The following attestation bundles were made for typing_schema-0.1.0-py3-none-any.whl:
Publisher:
python-publish.yml on kasancode/Typing-schema
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
typing_schema-0.1.0-py3-none-any.whl -
Subject digest:
b1a0407104139246dd70f1abb0c6de38a5ca7b31824eab38376cae4a99d68881 - Sigstore transparency entry: 719594814
- Sigstore integration time:
-
Permalink:
kasancode/Typing-schema@6e3fe97947592820b17caffa641132822db1c670 -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/kasancode
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@6e3fe97947592820b17caffa641132822db1c670 -
Trigger Event:
release
-
Statement type: