5

I've always used functools.wraps with my decorators, but today I've asked myself why?

def requires_auth(function):

    @functools.wraps(function)
    def wrapper(request, *args, **kwargs):
        ...
        return function(request, *args, **kwargs)

    return wrapper

This blog says:

Since decorator is simply a function that wraps original one so it will replace function.__name__ property to it’s own name and that can cause some misunderstanding during debugging your code and(or) using introspection(inspect/traceback module and etc. in some certain conditions).

So functools.wraps helps copying __name__, __doc__ of the wrapped function, but my question is who needs it?

This answer says:

If using a decorator always meant losing this information about a function, it would be a serious problem.

But is this a "serious problem"?

This page says:

One final point thing to keep in mind is that trying to check the __name__ and __doc__ of a wrapped function will get these values from the wrapper instead. This might mess things up for documentation generation tools or other kinds of code that rely on this information.

Ok, a valid point, but is this a critical problem?

I would rather not use functools.wraps because I use pdb a lot and if I get properties of a function with other function's properties it can make debugging harder.

Explicit is better than implicit.

All the information I found in favor of always using functools.wraps does not look convincing. Have I missed anything?

Community
  • 1
  • 1
warvariuc
  • 57,116
  • 41
  • 173
  • 227
  • 2
    *"...is this a critical problem?"* - well, are you using those kinds of tools? – jonrsharpe Nov 25 '15 at 15:36
  • 1
    You can distinguish between decorators for your own use -- in which case it is probably somewhat superfluous and decorators that are meant for others to use, possibly as part of a library. Wrapping the decorators might make them more transparent to other users – John Coleman Nov 25 '15 at 15:36
  • 1
    Echoing jonrsharpe, I'm a little confused at the motivation of your question here. "Is [messing up documentation generators] a critical problem?" Well, if you're the author of an automatic documentation generator, I'd say you'd certainly think so... – Two-Bit Alchemist Nov 25 '15 at 15:39
  • I'm curious about the inverse of this question as well. Why _wouldn't_ you want to do this? Sure, there are probably some cases where you'd want the name of wrapping functions to appear in, say, server logs. But in general, isn't having the "real" name of the function in the logs what you want? What's the trade-off for not doing this, given it's one import and one simple decorator? – Two-Bit Alchemist Nov 25 '15 at 15:43

0 Answers0