2
Validator for repeating items.
5
filters = warnings.filters[:]
6
warnings.simplefilter('ignore', DeprecationWarning)
8
warnings.filters = filters
14
from api import NoDefault, Invalid
15
from compound import CompoundValidator, to_python, from_python
19
class ForEach(CompoundValidator):
22
Use this to apply a validator/converter to each item in a list.
26
ForEach(AsInt(), InList([1, 2, 3]))
28
Will take a list of values and try to convert each of them to
29
an integer, and then check if each integer is 1, 2, or 3. Using
30
multiple arguments is equivalent to::
32
ForEach(All(AsInt(), InList([1, 2, 3])))
34
Use convert_to_list=True if you want to force the input to be a
35
list. This will turn non-lists into one-element lists, and None
36
into the empty list. This tries to detect sequences by iterating
37
over them (except strings, which aren't considered sequences).
39
ForEach will try to convert the entire list, even if errors are
40
encountered. If errors are encountered, they will be collected
41
and a single Invalid exception will be raised at the end (with
44
If the incoming value is a set, then we return a set.
47
convert_to_list = True
52
def attempt_convert(self, value, state, validate):
53
if self.convert_to_list:
54
value = self._convert_to_list(value)
55
if self.if_empty is not NoDefault and not value:
57
if self.not_empty and not value:
58
if validate is from_python and self.accept_python:
61
self.message('empty', state),
66
is_set = isinstance(value, (set, Set))
68
previous_index = getattr(state, 'index', NoDefault)
69
previous_full_list = getattr(state, 'full_list', NoDefault)
71
state.full_list = value
73
for sub_value in value:
78
for validator in self.validators:
80
sub_value = validate(validator, sub_value, state)
88
new_list.append(sub_value)
91
new_list = set(new_list)
95
'Errors:\n%s' % '\n'.join([unicode(e) for e in errors if e]),
100
if state is not None:
101
if previous_index is NoDefault:
104
except AttributeError:
107
state.index = previous_index
108
if previous_full_list is NoDefault:
111
except AttributeError:
114
state.full_list = previous_full_list
116
def empty_value(self, value):
119
class _IfMissing(object):
120
def __get__(self, obj, type=None):
123
elif obj._if_missing is ForEach._if_missing:
126
return obj._if_missing
127
def __set__(self, obj, value):
128
obj._if_missing = value
129
def __delete__(self, obj):
130
obj._if_missing = NoDefault
132
if_missing = _IfMissing()
135
def _convert_to_list(self, value):
136
if isinstance(value, (str, unicode)):
140
elif isinstance(value, (list, tuple)):
146
## @@: Should this catch any other errors?: