pyvalid’s documentation

The pyvalid is the Python validation tool for checking a function’s input parameters and return values.

Purposes of the pyvalid package:

  1. Provide an ability to validate a user input (such as usernames, phone numbers, emails, dates and times, etc) and minimize the amount of code required for the implementation of the comprehensive validation systems;

  2. Add an additional layer of dynamic code analysis for the development and testing stages — pyvalid will raise the exception if a function accepts or returns unexpected values and it’s always possible to disable pyvalid in production if needed.

  3. Help to catch runtime issues.

How to install

  • With PyPI: pip install -U pyvalid

  • Manually: python setup.py install

How to use

The schema below reveals the general structure of the pyvalid package:

_images/pyvalid-map.png

The package consists of two decorators: accepts and returns, which validates the function’s input and output values accordingly. To know how to validate the data, accepts and returns decorators should receive the information about excepted values/types/validators.

The very basic example below shows how to use accepts and returns decorators.

from pyvalid import accepts, returns


@accepts(int, int)
@returns(float)
def divide(num_1, num_2):
    return num_1 / num_2

divide(8, 42)
# Returns float value

divide('Python', 42)
# Raises the ArgumentValidationError exception, since the 1st argument is
# the str value, when we're expecting int values only.

If just specifying an expected type or value is not enough, then it’s worth to use the custom validator. All the built-in validators are located in the pyvalid.validators module and it’s also possible to create a new one using the is_validator decorator or through extending the AbstractValidator class.

We can flexibly control the state of the pyvalid validation using the pyvalid.switch module. This module provides an ability to switch the pyvalid on/off.

In most cases, it’s worth to use the pyvalid features to validate incoming/outcoming data, such as: user input, the data sent to the API, etc.

But it’s also possible to use the pyvalid package as a part of the CI/CD processes only:

  1. Apply the accepts and returns decorators to all needed functions and methods.

  2. Perform unit testing, integration testing, etc.

  3. The accepts and returns decorators will raise exceptions in case if the input/output data is not valid.

  4. Collect information about raised exceptions and fix the code, which causes them.

  5. Turn off the pyvalid before going live in order to avoid unnecessary exceptions in production.

License

This project is distributed under the MIT License.

Indices and tables