Is this considered black magic?

Achim Domma achim.domma at syynx.de
Sun Nov 11 11:25:22 EST 2001


Hi,

I would try to put your foreach in a class :

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



class FktCall:
    def __init__(self,name,fkt):
        self.name = name
        self.fkt = fkt

    def __call__(self,*args):
        return self.fkt(self.name,*args)

class ClusteredCall:
    def __init__(self,*items):
        self.items = items

    def do_foreach(self,name_key,*args):
        for o in self.items:
            try:
                getattr(o, name_key)(*args)
            except AttributeError:
                pass

    def __getattr__(self,attr):
        return FktCall(attr,self.do_foreach)


##########################
if __name__ == '__main__':

    cluster = ClusteredCall(Ham(),Eggs(),Spam())

    cluster.shout('sandwich')
    cluster.speak_up('test')

-----------------------

I'm no Python Expert and don't know how much performance you loose due to
the extra level of indirection. But in my opinion the client code (i.e.
cluster.shout(...)) is much more readable this way.

greetings
Achim





More information about the Python-list mailing list