Skip to main content

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, and pydantic.BaseModel to 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 to typing_to_schema or function_to_schema to handle custom types. If it returns a schema the converter will use it.
  • annotated_doc_handler: pass a callback to extract documentation from Annotated[...] 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

typing_schema-0.1.0.tar.gz (7.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

typing_schema-0.1.0-py3-none-any.whl (6.0 kB view details)

Uploaded Python 3

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

Hashes for typing_schema-0.1.0.tar.gz
Algorithm Hash digest
SHA256 936c680f9314f2d488d3c4dc69e3488e5bc7040fcd2f0ad54426fd708f38bbb0
MD5 ed3fbef56bbe01f7b8702e9d30ab3525
BLAKE2b-256 fbaa266fe03ec54db741f5623dcd80575b644de4528e6bea5b832fe20116887a

See more details on using hashes here.

Provenance

The following attestation bundles were made for typing_schema-0.1.0.tar.gz:

Publisher: python-publish.yml on kasancode/Typing-schema

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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

Hashes for typing_schema-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b1a0407104139246dd70f1abb0c6de38a5ca7b31824eab38376cae4a99d68881
MD5 ac940200fd25af92de3805e08e9f1df6
BLAKE2b-256 f53c110bd2f425f75b97a9715a615e37410471c68bf6b95518dcf65ef980baff

See more details on using hashes here.

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

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page