pyvalid
pyvalid is a Python data validation tool that allows for easy validation of function's input parameters and return values using `accepts` and `returns` decorators. The current version is 1.0.4, released in October 2020, suggesting a low release cadence.
Warnings
- gotcha The library has not been updated since October 2020. This indicates potential for limited or no support for newer Python versions (e.g., Python 3.10 and above) or a slower response to bug fixes and community contributions.
- gotcha The official quickstart example uses `eval()` with string interpolation. If the `operator` or any other input parameters in such a context were to come from untrusted user input, it could lead to a severe security vulnerability allowing arbitrary code execution.
- gotcha The quickstart examples primarily focus on decorator usage but do not explicitly demonstrate how to catch the specific exceptions (`InvalidArgumentNumberError`, `ArgumentValidationError`, `InvalidReturnType`) raised by `pyvalid` upon validation failure. Lack of proper exception handling can lead to ungraceful program termination.
Install
-
pip install pyvalid
Imports
- accepts
from pyvalid import accepts, returns
- returns
from pyvalid import accepts, returns
Quickstart
from pyvalid import accepts, returns, InvalidArgumentNumberError, ArgumentValidationError, InvalidReturnType
@returns(int, float)
@accepts(str, (int, 2.0), (int, float))
def calc(operator, val1, val2, val3):
# WARNING: Using eval() with untrusted input is a security risk.
# This is for demonstration purposes based on the official example.
expression = '{v1} {op} {v2} {op} {v3}'.format(
op=operator, v1=val1, v2=val2, v3=val3
)
return eval(expression)
try:
# Returns int value: 24
print(calc('*', 2, 3, 4))
# Returns float value: 24.0
print(calc(operator='*', val1=2, val2=3.0, val3=4))
# This will raise an ArgumentValidationError because 'val1' should be int or 2.0, not a string
# print(calc('+', 1, 'invalid', 3))
# Example of a call that would fail if uncommented and demonstrate exception handling
# calc('+', 1, 'invalid_type', 3)
# Example that would fail if return type is wrong
# @returns(str)
# def bad_return():
# return 123
# bad_return()
except (InvalidArgumentNumberError, ArgumentValidationError, InvalidReturnType) as e:
print(f"Validation Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")