Search code examples
pythonvalidationvoluptuous

Are there any conditional rules for voluptuous?


Is there any way to define conditional rules using voluptuous?

Here's the schema I have:

from voluptuous import Schema, All, Any

schema = Schema({
    'resolution': All(str, Any('1920x1080', '1280x720')),
    'bitrate': 20,
})

That's ok, but now I want to validate bitrate value based on resolution value. If I have 1920x1080 as resolution, than I need to be shure that bitrate is one of these values: 20, 16, 12, 8; and when it's 1280x720 then bitrate should be one of these: 10, 8, 6, 4.

How can I do that? There's info on the project's github page but I can't find my case there.


Solution

  • Voluptuous supports custom validation functions [1], but they only receive as input parameter the value being currently validated, not any other previously validated values. This means trying to do something like 'bitrate': (lambda bitrate, resolution: Any(20, 16, 12, 8) if bitrate in (...) else Any (10, 8, 6, 4)) will unfortunately not work.

    You can try using 'bitrate': Any(20, 16, 12, 10, 8, 6, 4) and then performing secondary validation yourself to make sure it's consistent with resolution.

    Another approach could be to write a validator function for the complete dictionary, where the function would check both resolution and bitrate at the same time, though this way you'd be writing some code you normally get for free from voluptuous.

    [1] https://github.com/alecthomas/voluptuous#validation-functions