Iterate through a list calling functions

Kent Johnson kent37 at tds.net
Sun Jun 5 22:07:38 EDT 2005


George Sakkis wrote:
> That's a typical case for using an OO approach; just make a class for
> each validator and have a single polymorphic validate method (I would
> make validators __call__able instead of naming the method 'validate'):
> 
> # Abstract Validator class; not strictly necessary but good for
> documentation
> class Validator(object):
>     def __call__(self,field,value):
>         '''Validate a value for this field.
>         Return a string representation of value on success, or None on
> failure.
>         '''
>         raise NotImplementedError("Abstract method")
> 
> 
> class DecimalValidator(Validator):
>     def __call__(self,name,value):
>         '''Test whether numeric value is a decimal.'''

Why is this better than an isDecimal function?

def isDecimal(name, value):
    ''' Test whether numeric value is a decimal.'''

seems simpler and more straightforward to me.

> def validateField(name, value, validators):
>     """ Validates field input """
>     results = {}
>     for validate in validators:
>         result = validate(name,value)
>         if result is not None:
>             results[name] = result
>             # XXX: if more than one validators succeed,
>             # all but the last result will be overwritten
>     return results

No change needed in the loop above...
> 
> # test
> validators = [DecimalValidator(), ZipCodeValidator()]
validators = [ isDecimal, isZipCode ]

Kent



More information about the Python-list mailing list