On Wednesday, November 30, 2011 5:16:59 PM UTC-5, lyn2py wrote:
>
> Thanks Anthony.
>
> That's interesting syntax to use a validator!
>
Well, the validators are mostly intended to be used for validating form 
fields. They are callable objects, so you instantiate a validator like 
IS_SLUG(), which is an object with a __call__ method that takes a value and 
validates it. The __call__ method returns a tuple, which is the (possibly 
transformed) value and either an error message or None. A few of the 
validators, such as IS_SLUG, actually transform the input value rather than 
simply checking it, so they can also be used independently for their 
transformation effects. Of course, in that case, the required syntax seems 
a bit awkward:

IS_SLUG()  # creates a callable object - usually passed as the 'requires' 
arg to Field()
IS_SLUG()('My Title')  # passes a value to the __call__ method of the 
validator object
IS_SLUG()('My Title')[0]  # extracts the returned value, which is the first 
element of the returned tuple

To make it easier, you can write your own helper:

make_slug = lambda v: IS_SLUG()(v)[0]

Then do:

title_slug = make_slug('My Title')

This is like Bruno's compute example. You could also make a more general 
helper that works with any validator:

>>> transform = lambda v, validator: validator()(v)[0]
>>> transform('my title', IS_SLUG)
'my-title'
>>> transform('My Title', IS_UPPER)
'MY TITLE'

Anthony

Reply via email to