安装 pydantic
pip install 'pydantic[dotenv]'
执行以下代码
from pydantic import Field, validate_arguments, ValidationError
@validate_arguments
def my_func(i: int = Field(..., ge=1, le=100)):
# 你的函数逻辑在这里
print(f"Input {i} is within the valid range.")
try:
my_func(50) # 正确的输入,应该打印"Input 50 is within the valid range."
my_func(150) # 错误的输入,会引发ValidationError异常
except ValidationError as e:
print(f"Invalid input: {e}")
输出
Input 50 is within the valid range.
Invalid input: 1 validation error for MyFunc
i
ensure this value is less than or equal to 100 (type=value_error.number.not_le; limit_value=100)