Gregor Horvath
2010-09-11 20:09:41 UTC
Hello,
For late evaluation I need a OneOf Validator with a list argument as
callable. (or list / tuple)
I therefore made on enhanced version.
Is a patch / test desired?
Greg
class OneOf(FancyValidator):
"""
Tests that the value is one of the members of a given list.
If ``testValueList=True``, then if the input value is a list or
tuple, all the members of the sequence will be checked (i.e., the
input must be a subset of the allowed values).
Use ``hideList=True`` to keep the list of valid values out of the
error message in exceptions.
...
Invalid: Value must be one of: 1; 2; 3 (not 4)
...
Invalid: Value must be one of: 1; 2; 3 (not [2, 3, [1, 2, 3]])
"""
list = None
testValueList = False
hideList = False
__unpackargs__ = ('list',)
messages = {
'invalid': _("Invalid value"),
'notIn': _("Value must be one of: %(items)s (not %(value)r)"),
}
def validate_python(self, value, state):
try:
self.list = self.list()
except TypeError:
pass
if self.testValueList and isinstance(value, (list, tuple)):
for v in value:
self.validate_python(v, state)
else:
if not value in self.list:
if self.hideList:
raise Invalid(self.message('invalid', state),
value, state)
else:
items = '; '.join(map(str, self.list))
raise Invalid(self.message('notIn', state,
items=items,
value=value),
value, state)
For late evaluation I need a OneOf Validator with a list argument as
callable. (or list / tuple)
I therefore made on enhanced version.
Is a patch / test desired?
Greg
class OneOf(FancyValidator):
"""
Tests that the value is one of the members of a given list.
If ``testValueList=True``, then if the input value is a list or
tuple, all the members of the sequence will be checked (i.e., the
input must be a subset of the allowed values).
Use ``hideList=True`` to keep the list of valid values out of the
error message in exceptions.
oneof = OneOf([1, 2, 3])
oneof.to_python(1)
1oneof.to_python(1)
oneof.to_python(4)
Traceback (most recent call last):...
Invalid: Value must be one of: 1; 2; 3 (not 4)
oneof(testValueList=True).to_python([2, 3, [1, 2, 3]])
[2, 3, [1, 2, 3]]oneof.to_python([2, 3, [1, 2, 3]])
Traceback (most recent call last):...
Invalid: Value must be one of: 1; 2; 3 (not [2, 3, [1, 2, 3]])
"""
list = None
testValueList = False
hideList = False
__unpackargs__ = ('list',)
messages = {
'invalid': _("Invalid value"),
'notIn': _("Value must be one of: %(items)s (not %(value)r)"),
}
def validate_python(self, value, state):
try:
self.list = self.list()
except TypeError:
pass
if self.testValueList and isinstance(value, (list, tuple)):
for v in value:
self.validate_python(v, state)
else:
if not value in self.list:
if self.hideList:
raise Invalid(self.message('invalid', state),
value, state)
else:
items = '; '.join(map(str, self.list))
raise Invalid(self.message('notIn', state,
items=items,
value=value),
value, state)