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 typing_schema 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.1.tar.gz (7.8 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.1-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file typing_schema-0.1.1.tar.gz.

File metadata

  • Download URL: typing_schema-0.1.1.tar.gz
  • Upload date:
  • Size: 7.8 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.1.tar.gz
Algorithm Hash digest
SHA256 f5bc0fddfb8fc177d624681e139f30371cc717fc43dfce9972c132b4e2b9c111
MD5 a368c2039fcc45f55a6de54e4463cd89
BLAKE2b-256 4ffd5fbe250092008cb1943ee1df8fcead1141c126b7bb8666d33d5d776188dd

See more details on using hashes here.

Provenance

The following attestation bundles were made for typing_schema-0.1.1.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.1-py3-none-any.whl.

File metadata

  • Download URL: typing_schema-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 6.1 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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e4b75631f51d83796b0642844061610b094a01731d4e7f9278d9cc6e1e9a9722
MD5 3e73f8d2d7dee8de92a68a49cf084730
BLAKE2b-256 5187962b4795f8836dd342d465270ebffcb9574c110b3b8d83a98c2c49b9d094

See more details on using hashes here.

Provenance

The following attestation bundles were made for typing_schema-0.1.1-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