0

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?

gore
  • 551
  • 2
  • 20
nowox
  • 25,978
  • 39
  • 143
  • 293

1 Answers1

2

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.

gore
  • 551
  • 2
  • 20