Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prioritize Optionals based on one level of depth traversal. Close #44, #45. #54

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,8 @@ data matches:

>>> from schema import Optional
>>> Schema({Optional('color', default='blue'): str,
... str: str}).validate({'texture': 'furry'})
{'color': 'blue', 'texture': 'furry'}
... Optional(str): str}).validate({})
{'color': 'blue'}

Defaults are used verbatim, not passed through any validators specified in the
value.
Expand Down
46 changes: 33 additions & 13 deletions schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,19 +77,29 @@ def validate(self, data):


def priority(s):
"""Return priority for a given object."""
"""Return the priority with which a schema should be tried against an
object.

A priority is a tuple of at least 1 "flavor". Sorted lexically, they
determine the order in which to try schemata against data.

"""
if type(s) in (list, tuple, set, frozenset):
return ITERABLE
if type(s) is dict:
return DICT
if issubclass(type(s), type):
return TYPE
if hasattr(s, 'validate'):
return VALIDATOR
if callable(s):
return CALLABLE
ret = ITERABLE
elif type(s) is dict:
ret = DICT
elif issubclass(type(s), type):
ret = TYPE
elif hasattr(s, 'validate'):
# Deletegate to the object's priority() method if there is one,
# allowing it to traverse into itself and return a compound priority
# like (2, 3):
return getattr(s, 'priority', lambda: (VALIDATOR,))()
elif callable(s):
ret = CALLABLE
else:
return COMPARABLE
ret = COMPARABLE
return (ret,)


class Schema(object):
Expand All @@ -104,7 +114,7 @@ def __repr__(self):
def validate(self, data):
s = self._schema
e = self._error
flavor = priority(s)
flavor = priority(s)[0]
if flavor == ITERABLE:
data = Schema(type(s), error=e).validate(data)
return type(s)(Or(*s, error=e).validate(d) for d in data)
Expand Down Expand Up @@ -187,6 +197,9 @@ def validate(self, data):
else:
raise SchemaError('%r does not match %r' % (s, data), e)

def priority(self):
return (VALIDATOR,)


MARKER = object()

Expand All @@ -200,10 +213,17 @@ def __init__(self, *args, **kwargs):
super(Optional, self).__init__(*args, **kwargs)
if default is not MARKER:
# See if I can come up with a static key to use for myself:
if priority(self._schema) != COMPARABLE:
if priority(self._schema)[0] != COMPARABLE:
raise TypeError(
'Optional keys with defaults must have simple, '
'predictable values, like literal strings or ints. '
'"%r" is too complex.' % (self._schema,))
self.default = default
self.key = self._schema

def priority(self):
"""Dig in one level so Optional('foo') takes precedence over
Optional('str'). We could go deeper if we wanted.

"""
return super(Optional, self).priority() + priority(self._schema)
7 changes: 7 additions & 0 deletions test_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,13 @@ def test_dict_optional_keys():
Optional('b'): 2}).validate({'a': 1, 'b': 2}) == {'a': 1, 'b': 2}


def test_delegated_priority():
"""Make sure compound, instance-delegated priorities work."""
# Optional('a') should take precedence, because it's more specific.
assert Schema({Optional(str): 1,
Optional('a'): 2}).validate({'a': 2}) == {'a': 2}


def test_dict_optional_defaults():
# Optionals fill out their defaults:
assert Schema({Optional('a', default=1): 11,
Expand Down