alecthomas / voluptuous

CONTRIBUTIONS ONLY: Voluptuous, despite the name, is a Python data validation library.
https://pypi.org/project/voluptuous
BSD 3-Clause "New" or "Revised" License
1.82k stars 218 forks source link

Inclusive should support default values #381

Open nickovs opened 5 years ago

nickovs commented 5 years ago

The Inclusive schema builder does not support default values even though it inherits from Optional, which does support them. It would be valuable if defaults were supported for situations such as this:

dimensions = Schema({
    Inclusive("width", "dims", default=1024): Coerce(int),
    Inclusive("height", "dims", default=576): Coerce(int),
}

In general, when using Inclusive to enforce "all or nothing", having default values for the "nothing" case would be very helpful.

sfelf commented 5 years ago

Sorry dumb question here... how is this different from:

dimensions = Schema({
    Optional("width", default=1024): Coerce(int),
    Optional("height", default=576): Coerce(int),
}
nickovs commented 5 years ago

If you put a set of values in an Inclusive group then either all of the items in the group need to be supplied or none of them can be. It is reasonable to want to set a default value for the set of variables while preserving that behaviour. With your schema dimensions({'width':17}) returns {'width':17, 'height':576} whereas with my schema it would be an error to leave it half-specified.

sfelf commented 5 years ago

Ok so then how does the default value come into play? If you are expecting dimensions({'width':17}) to raise an Invalid are you expecting dimensions({}) to return {'width': 1024, 'height': 576}?

nickovs commented 5 years ago

Yes, that is exactly the behaviour I'm looking for. A schema that uses Inclusive requires the user to specify all or nothing. If they specify nothing then you get the default values. What you don't want is to get inconsistent results because someone half-specified what was needed. In the example above, allowing the default value for height to be used would give a box with a crazy aspect ratio and is likely not what was wanted.

sfelf commented 5 years ago

Thank you for the explanation. I wasn't expecting the inclusive check to occur before default created the key with the default value if the key didn't exist. Updating the documentation to explain how the default value works on Inclusive would be helpful.