nowox
nowox

Reputation: 29096

Voluptuous at least one-of key in dictionary validation?

Let's say I would like a dictionary with at least one of the three key foo', 'bar', baz`. The following would allow an empty set.

Schema({
  'foo': str,
  'bar': int,
  'baz': bool
})

Unfortunately, I cannot do this:

Any(
  Schema({'foo': str}),
  Schema({'bar': int}),
  Schema({'baz': bool)
)

What would be the best way of doing it?

Upvotes: 0

Views: 1211

Answers (1)

gore
gore

Reputation: 571

dictionary with at least one of the three key foo', 'bar', baz

How to reach this: it's is already described on github voluptuous project.

Solution (adopted for your example):

from voluptuous import All, Any, Optional, Required, Schema

key_schema = Schema({
    Required(
        Any('foo', 'bar', 'baz'),
        msg="Must specify at least one of ['foo', 'bar', 'baz']"): object
})

data_schema = Schema({
    Optional('foo'): str,
    Optional('bar'): int,
    Optional('baz'): bool,
})

s = All(key_schema, data_schema)

So, the s is the final Schema that you can use in your code and tests.

Upvotes: 2

Related Questions