executing list of methods (and collecting results)

Bjoern Schliessmann usenet-mail-0306.20.chr0n0ss at spamgourmet.com
Thu Sep 20 20:39:54 EDT 2007


Gerardo Herzig wrote:

> 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).

(inside class definition -- untested)
validators = {"is a number": is_really_a_number,
              "is even": is_even,
              "is greater than zero": is_greater_than_zero}

def collect_validators(self):
   return [desc for desc, func in self.validators.items() if func()]
 
> My first approach is:

... no method, but a generator. Executing it will give you a
generator object instead of a result list.
 
> [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', 

IMHO, it doesn't look natural. It depends on what you want to
achieve. This generator will need to be iterated over until it
is "exhausted".

> but...im calling every method twice here?

No. Methods are only called if you apply the function call
operator, "()".

BTW, I hope you don't really want to test a number to be greater
than zero, or even, by using an own method, respectively, just to
test this.

Regards,


Björn

-- 
BOFH excuse #321:

Scheduled global CPU outage




More information about the Python-list mailing list