Is this considered black magic?

Peter Hansen peter at engcorp.com
Sun Nov 11 11:01:51 EST 2001


(Reposted... previous one stupidly read object.getattr(name_key), which
I *always* type first for some reason.  *This* post actually tested. :)

Laura Creighton wrote:
> 
> I want to do something which is conceptually very simple.  Given a list of
> objects, call make everybody call the same method you want to run.  Sort
> of like apply(), but for methods.
[...]
> def foreach(name_key, object_list, *args):
>     print 'foreach: args are ' + `args`
>     for object in object_list:
>         try:
>             object.__class__.__dict__[name_key](object, *args)
>         except KeyError:
>             pass

How about using getattr() instead?  Then the core above would be 
more like this:

method = getattr(object, name_key)  # returns bound method
if callable(method):
    try:
         method(*args)
    except:
         print 'Call failed!'

Slightly less "black-magical" ?

(I personally would pre-qualify the method so that I could wrap
the call with a catch-all try/except because otherwise I wouldn't
know whether the KeyError, for example, came from the method call
or the attempt to find the name in the dictionary.)

[...]
>     foreach ('say', [h, e, s])
> 
>     foreach('speak_up', [e])
>     foreach('speak_up', [h, e, s], 'sandwich')
>     foreach('speak_up', [h, e, s], None) #can i pass None?
> 
>     foreach('shout', [h, e, s], 'sandwich')
>     foreach('shout', [h, e, s], 'sandwich', 'beer')

I wouldn't put the list of objects second.  Mentally I think 
it should read "here's a list of thing(s), and for each item
in the list, call this method with these arguments."

This isn't black magic, this is Python's awesome introspection! :)

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



More information about the Python-list mailing list