Is this considered black magic?

Just van Rossum just at letterror.com
Sun Nov 11 16:05:21 EST 2001


Laura Creighton wrote:

> Okay, new version:
> 
> def foreach(object_list, method_name, *args):
>     for object in object_list:
>         try:
>             method = getattr(object, method_name)
>         except AttributeError:
>             pass
>         else:
>             if callable(method):
>                 method(*args)
> 
> Did I miss something?

One slight improvement that I didn't think of before:

def foreach(object_list, method_name, *args):
    for object in object_list:
        method = getattr(object, method_name, None)
        if method is not None and callable(method):
            method(*args)

I think three-arg getattr() is faster than catching an exception.

(I would leave out the callable() test, but then again, I don't
know your exact needs.)

Just



More information about the Python-list mailing list