Skip to content

Commit

Permalink
maybe can be something of the given type or None
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreaCrotti committed Oct 10, 2016
1 parent 99fb7bd commit ca06496
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
15 changes: 14 additions & 1 deletion voluptuous/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
Schema, Required, Optional, Extra, Invalid, In, Remove, Literal,
Url, MultipleInvalid, LiteralInvalid, NotIn, Match, Email,
Replace, Range, Coerce, All, Any, Length, FqdnUrl, ALLOW_EXTRA, PREVENT_EXTRA,
validate, ExactSequence, Equal, Unordered, Number
validate, ExactSequence, Equal, Unordered, Number, Maybe
)
from voluptuous.humanize import humanize_error
from voluptuous.util import to_utf8_py2, u
Expand Down Expand Up @@ -544,6 +544,19 @@ def fn(arg):
fn(1)


def test_schema_decorator_no_args():
@validate(int, __return__=Maybe(int))
def fn(arg):
if arg == 0:
return None
else:
return arg

fn(1)
fn(0)



def test_schema_decorator_unmatch_return_with_args():
@validate(int, __return__=int)
def fn(arg):
Expand Down
8 changes: 8 additions & 0 deletions voluptuous/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,14 @@ def PathExists(v):
raise PathInvalid("Not a Path")


class Maybe(object):
def __init__(self, kind):
self.kind = kind

def __call__(self, v):
return v is None or isinstance(v, self.kind)


class Range(object):
"""Limit a value to a range.
Expand Down

0 comments on commit ca06496

Please sign in to comment.