Is this considered black magic?

Brad Bollenbach bbollenbach at home.com
Sun Nov 11 10:59:05 EST 2001


"Laura Creighton" <lac at strakt.com> wrote in message
news:mailman.1005485895.7082.python-list at python.org...
> 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.

apply() is made for methods as well. All it cares about is that you pass it
a callable object as its first argument. Whether said callable object is
foo, or x.foo is irrelevant. Either one is callable.

> This is what I came up with:
>
> class Ham:
>     def say(self):
>         print "I am Ham, and I don't want any arguments, thank you."
>
>     def speak_up(self, arg):
>         print 'I am Ham, and my arguments are %s' % arg
>
> class Eggs:
>     def speak_up(self, arg='bacon'):
>         print 'I am Eggs, and my arguments are %s' % arg
>
> class Spam:
>     def shout(self, arg1, arg2='sausage'):
>         print 'I AM SPAM AND MY ARGUMENTS ARE %s AND %s' % (arg1, arg2)
>
> 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
>
> ##########################
> if __name__ == '__main__':
>
>     h=Ham()
>     e=Eggs()
>     s=Spam()
>
>     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')
> --------------
>
> This works:

Indeed, but doesn't buy you much over a simple:

for x in [h, e, s]:
     try:
        x.speak_up()        # or apply(x.speak_up, (args, go, here)) if
you're so inclined.
     except AttributeError:
        pass

etc.

> foreach: args are ()
> I am Ham, and I don't want any arguments, thank you.
> foreach: args are ()
> I am Eggs, and my arguments are bacon
> foreach: args are ('sandwich',)
> I am Ham, and my arguments are sandwich
> I am Eggs, and my arguments are sandwich
> foreach: args are (None,)
> I am Ham, and my arguments are None
> I am Eggs, and my arguments are None
> foreach: args are ('sandwich',)
> I AM SPAM AND MY ARGUMENTS ARE sandwich AND sausage
> foreach: args are ('sandwich', 'beer')
> I AM SPAM AND MY ARGUMENTS ARE sandwich AND beer
> ----------------
>
> But is it white, grey, or black magic?  Is there a better way I should
have
> done?  Suggestions on what to name the function gratefully welcomed.
>
> Laura Creighton

Hope that helps,

Brad





More information about the Python-list mailing list