Is this considered black magic?

Peter Hansen peter at engcorp.com
Mon Nov 12 00:08:23 EST 2001


Just van Rossum wrote:
> 
> 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.)

Good point with the default return from getattr(), but 
we differ on the latter point.  *I* would leave out the
check for None, since callable(None) returns false, but
then again, maybe we should be leaving both of them out!

If we are assuming the object has a method with the
specified name, both tests are redundant.  If we want
to handle objects which don't even have such an attribute
by silently ignoring them, I suppose we should also
ignore objects which have an attribute with the right
name but which are not callable...

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list