[Python-ideas] returning anonymous functions

Scott Dial scott+python-ideas at scottdial.com
Mon Dec 15 19:52:20 CET 2008

Mathias Panzenböck wrote:
> It is a very common case to return a nested function, e.g. in a decorator:
> def deco(f):
>    def _f(*args,**kwargs):
>       do_something()
>       try:
>          return f(*args,**kwargs)
>       finally:
>          do_something_different()
>    return _f

Is is really that common? In this case, you are misrepresenting the
pattern. The appropriate version of this would require references to _f
to make it's signature match that of f's, and therefore this entire
argument is specious. In reality, the number of times you can get away
with returning a truly anonymous function (that isn't a glorified
lambda) is rare, I think.

def deco(f):
    def _f(*args,**kawrgs):
    functools.update_wrapper(_f, f)
    return _f


def deco(f):
    def _f(*args,**kawrgs):
    return _f

Even in the second case, it would be awkward to inline with the return
statement because of the need to invoke a decorator.


Scott Dial
scott at scottdial.com
scodial at cs.indiana.edu

More information about the Python-ideas mailing list