Search code examples
pythonpython-3.xvalidationtypingcerberus

cerberus schema validator for tuples


I have a variable declaration as follows

my_var = typing.List[typing.Tuple[int, int]]

and I want to write a validator as follows

schema_validator = "my_var": {
    "type": "list",
    "empty": False,
    "items": [
        {"type": "tuple"},
        {"items": [
            {"type": "int"}, {"type": "int"}
        ]}
    ]
}

In Cerberus documentation it does not specify a validator example for tuples.

How to accomplish this?


Solution

  • Given your typevar typing.List[typing.Tuple[int, int]], you expect an arbritrary length list of two-value tuples where each value is an integer.

    class MyValidator(Validator):
        # add a type definition to a validator subclass
        types_mapping = Validator.types_mapping.copy()
        types_mapping['tuple'] = TypeDefinition((tuple,), ())
    
    
    schema = {
        'type': 'list',
        'empty': False,
        'schema': {  # the number of items is undefined
            'type': 'tuple',
            'items': 2 * ({'type': 'int'},)
        }
    }
    
    validator = MyValidator(schema)
    

    It's important to understand the difference of the items and the schema rule.

    Mind that the default list type actually maps to the more abstract Sequence type and you might want to add another, stricter type for that.