how to repeat function definitions less

skip at pobox.com skip at pobox.com
Sun Mar 15 00:09:51 CET 2009


    I'm doing this in my code, how to make it define all this functions for me
    with lambda, I've been up for a while and cant seem to figure it out, whats
    the most efficient way to do it? with lambda? how? thx

    def red(self,value,color='red',level='INFO'):
        self.write(value,color,level)
    def gold(self,value,color='gold',level='INFO'):
        self.write(value,color,level)
    ...

How about using __getattr__?  Something like:

    def __getattr(self, attr):
        if attr in ("red", "gold", ...):
            return self.write_color

    def write_color(self, value, color, level="INFO"):
        self.write(value,color,level)

That still leaves you with the need to pass in the color though:

    self.red(value, "red")

which violates the DRY principle.  I'm sure brighter minds than mine will
come up with a better solution.

-- 
Skip Montanaro - skip at pobox.com - http://www.smontanaro.net/



More information about the Python-list mailing list