pydantic-function-models

0.1.11 · active · verified Wed Apr 15

A library designed to model Python function signatures using Pydantic, offering a modern alternative to the now-deprecated `ValidatedFunction` from Pydantic v1. It facilitates the validation of function arguments based on type hints, bridging compatibility gaps between Pydantic v1 and v2. The library is currently at version 0.1.11, with updates reflecting ongoing maintenance.

Warnings

Install

Imports

Quickstart

This example demonstrates how to wrap a Python function with `ValidatedFunction` to enable Pydantic-style argument validation. It shows both successful validation and how `ValidationError` is raised for invalid inputs.

from pydantic_function_models import ValidatedFunction

def add(a: int, b: int) -> int:
    return a + b

vf = ValidatedFunction(add)

# Example of validating arguments
args_to_validate = (1,)
kwargs_to_validate = {"b": 2}

# The library builds an internal Pydantic model for validation
# You need to map positional/keyword args to model fields
validated_data = vf.model.model_validate({
    "a": args_to_validate[0],
    "b": kwargs_to_validate["b"]
})

result = add(**validated_data.model_dump(exclude_unset=True))
print(f"Result: {result}")

# Example of invalid input
try:
    invalid_data = vf.model.model_validate({"a": "one", "b": 2})
except Exception as e:
    print(f"Validation error caught: {e}")

view raw JSON →