executing list of methods (and collecting results)

James Stroud jstroud at mbi.ucla.edu
Fri Sep 21 02:38:00 CEST 2007


Gerardo Herzig wrote:
> Hi all. Im in this situation: I want to perform several kind of 
> (validating) methods to a given value.
> Lets say i have a class named Number, and the following methods:
> is_really_a_number(),
> is_even(),
> is_greater_than_zero(),
> and so on. All of them returning booleans.
> 
> I want the collect_validators() method is to execute any of the above 
> methods, and collect their names as items of a list (wich will be the 
> collect_validators() return value).
> 
> My first approach is:
> 
> [code]
> def collect_validators(self):
>    v_dict = { 'is_really_a_number': is_really_a_number,
>                      'is_even': is_even,
>                      'is_greater_than_zero', is_greater_than_zero
>                   }
> 
>       for name, meth in v_dict.items():
>          result = meth()
>          if result: yield name
> [/code]
> 
> I wondering if is this a good pattern to apply, i like the way it looks 
> like, at least to me it looks `natural', but...im calling every method 
> twice here? One in v_dict and again on the dict iteration?
> 
> Any suggestion will be great!
> 
> Thanks!
> Gerardo

You are not calling every method twice. You are painstakingly typing out 
their names twice. But fortunately, functions and methods have a 
__name__ attribute which makes a this typing redundant. I would give 
your class instances a _validators attribute which is a list of 
validating methods, then make the generator like this:

def collect_validators(self):
   for v in self._validators:
     if v():
       yield v.__name__

James



More information about the Python-list mailing list