OneOf Validator list as callable
Gregor Horvath <gh-LfrpOBifzZo+ytmZ3SK/[email protected]> Sat, 11 Sep 2010 22:09:41 +0200
| Newsgroups | gmane.comp.python.formencode |
|---|---|
| Organization | Ing. Gregor Horvath - Industrieberatung & Softwareentwicklung |
| Message-ID | <20100911220941.05e577f6@valun> |
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.
Examples::
>>> oneof = OneOf([1, 2, 3])
>>> oneof.to_python(1)
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)
------------------------------------------------------------------------------
Start uncovering the many advantages of virtual appliances
and start using them to simplify application deployment and
accelerate your shift to cloud computing
http://p.sf.net/sfu/novell-sfdev2dev