Validations

Validations#

Added in version 0.2.6.

The ploomber_core.validate module makes it simple to validate user inputs and provide a meaningful message as output.

Let’s say we have a function that returns a fruit from a list of fruits.

def get_fruit(fruit):
    list_of_fruits = ["apple", "orange", "grape"]
    if fruit in list_of_fruits:
        return list_of_fruits[list_of_fruits.index(fruit)]

We can use it as follows:

get_fruit("apple")
'apple'

This function works well, however, what occurs when the user requests grapes or makes a typo with a misspelled string such as appel? Currently, the function returns None. To improve input validation and provide the user with a clearer understanding of the None value, we may want to implement some logic.

Our keys validator provides us with the ability to accomplish this task. It enables us to alert the user if grapes are missing or there has been a typo error. Furthermore, it even allows us to suggest alternative keys as options.

from ploomber_core import validate

To use keys validator we need to pass the valid values, the input value (which can also be a sequence or a set) and the name of the parameter.

def get_fruit(fruit):
    list_of_fruits = ["apple", "orange", "grape"]

    validate.keys(valid=list_of_fruits, passed=fruit, name="fruit")

    if fruit in list_of_fruits:
        return list_of_fruits[list_of_fruits.index(fruit)]

Now, we call the function with grapes as an input.

get_fruit("grapes")
---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
Cell In[5], line 1
----> 1 get_fruit("grapes")

Cell In[4], line 4, in get_fruit(fruit)
      1 def get_fruit(fruit):
      2     list_of_fruits = ["apple", "orange", "grape"]
----> 4     validate.keys(valid=list_of_fruits, passed=fruit, name="fruit")
      6     if fruit in list_of_fruits:
      7         return list_of_fruits[list_of_fruits.index(fruit)]

File ~/checkouts/readthedocs.org/user_builds/ploomber-core/checkouts/latest/src/ploomber_core/validate.py:73, in keys(valid, passed, name, show_matches)
     70     if len(input_matches) > 0:
     71         err_message += f"\nDid you mean {input_matches}?"
---> 73 raise ValidationError(err_message)

ValidationError: Error validating argument 'fruit', the following value isn't valid: 'grapes'. Valid values are: 'apple', 'grape', and 'orange'. 
Did you mean 'grape'?