from voluptuous import Invalid, Schema def validate_int(value): if not isinstance(value, int): raise Invalid('Expected an integer') return value schema = Schema(validate_int) try: res = schema('abc') except Invalid as e: print(e)
from voluptuous import Invalid, Schema def validate_choice(choices): def _validate_choice(value): if value not in choices: raise Invalid(f'Expected one of {choices}') return value return _validate_choice schema = Schema(validate_choice(['red', 'green', 'blue'])) try: res = schema('orange') except Invalid as e: print(e)In both examples, the ValidationError exception will be raised with a message indicating the validation failure. These examples demonstrate the use of the Invalid function in combination with the Schema function from the Voluptuous package library.