[Python-Dev] Re: 2.4a2, and @decorators

David Eppstein eppstein at ics.uci.edu
Tue Aug 3 20:52:22 CEST 2004

BTW, here's another use case I haven't seen suggested yet:

    def substitution_for(regexp):
        sub = re.compile(regexp).sub
        return lambda func: lambda text: sub(func,text)

e.g. (example from some recent code of mine, redone as a decorator)

    def camelspace(m):
        """Insert space into camelcase regexp match."""
        return m.group(0)[0]+' '+m.group(0)[1:]


    info.title = camelspace(info.basefilename)

Instead my current code defines a separate variable for the 
re.compile().sub object, then later has to put this variable together 
correctly with the undecorated camelspace function to perform the 
substitution.  Using decorators allows the sub and replacement function 
to become merged into a single object with a more intuitive API.
(Also, my actual code uses more than one of these substitutions...)

I don't generally prefer to use explicit lambdas but expanding them out 
with names makes the definition of substitution_for a lot longer without 
much readability gain in my eyes.

David Eppstein
Computer Science Dept., Univ. of California, Irvine

More information about the Python-Dev mailing list