halst/schema — pull request #19 by Rogdham (2013-05-18 17:08:00+00:00)
Title: Add default values handling. Fixes #12.

This PR adds a way to handle default values for optional keys, as requested by #12.

You can pass the `default` keyword argument quite everywhere to specify a default, and that default is used if the corresponding key is optional:

>>> Schema({'event': str,
... Optional('date'): Use(int, default=2012),
... }).validate({'event': 'First commit'})
{'date': 2012, 'event': 'First commit'}

You can also use the `Default` class, which wraps whatever you gave as the first argument, and tries to find the appropriate value (here `0` for an `int`):

>>> Schema({'account': str,
... Optional('amount'): Default(int),
... }).validate({'account': 'Piggy bank'})
{'account': 'Piggy bank', 'amount': 0}

Of course, your need to give a proper default value, or else it complains, raising a `ValueError` (I think it is important that this is not a `SchemaError`, because that one means that the programmer made a mistake, nothing to do with the user data to validate):

>>> Use(int, default='two')
Traceback (most recent call last):
…
ValueError: Use() does not validate its default: two

And in case your optional key is a `type`, you can specify its default value as well:

>>> Schema({
... Optional(int, default=42): Or(1, 2, 3, 4, default=3)
… }).validate({})
{42: 3}

Tell me what you think!