pyvalid

1.0.4 · active · verified Wed Apr 15

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

Install

Imports

Quickstart

This example demonstrates how to use the `@accepts` and `@returns` decorators to validate function arguments and return values. It also includes basic error handling for the exceptions raised by `pyvalid`.

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}")

view raw JSON →