Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 245
Dmitrii Mikhailov Avatar asked Jun 14 '14 17:06

Dmitrii Mikhailov


2 Answers

My solution for a similar problem is to do something like

from voluptuous import Schema, Any

lo_res = Schema({'resolution': '1280x720', 'bitrate': Any(10, 8, 6, 4)})
hi_res = Schema({'resolution': '1920x1080', 'bitrate': Any(20, 16, 12, 8)})
schema = Any(lo_res, hi_res)

This will give you proper validation, although the error messages can get a bit cryptic. You can write a more customized version of Any to improve the error messages.

like image 155
Dave Avatar answered Nov 12 '22 09:11

Dave


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

like image 25
mpavlov Avatar answered Nov 12 '22 07:11

mpavlov