pydantic-function-models
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
- deprecated The `ValidatedFunction` class from Pydantic v1 is deprecated in Pydantic v2. This library provides a compatible `ValidatedFunction` for Pydantic v2 environments.
- gotcha Avoid using reserved parameter names such as `v__args` and `v__kwargs` in your function signatures, as these could conflict with the internal validation logic of `pydantic-function-models`.
- gotcha For simple function argument validation without needing the full function signature modeling provided by `ValidatedFunction`, Pydantic v2 offers the `@validate_call` decorator, which might be a more direct solution.
- gotcha Mixing Pydantic v1 and v2 models within a single application can lead to compatibility issues, especially with nested models. While `pydantic-function-models` helps with function validation, general migration strategies for `BaseModel` compatibility should be followed.
Install
-
pip install pydantic-function-models
Imports
- ValidatedFunction
from pydantic import ValidatedFunction
from pydantic_function_models import ValidatedFunction
Quickstart
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}")