In a comment on this answer to another question, someone said that they weren’t sure what functools.wraps was doing. So, I’m asking this question so that there will be a record of it on StackOverflow for future reference: what does functools.wraps do, exactly?
In a comment on this answer to another question , someone said that they
Share
When you use a decorator, you’re replacing one function with another. In other words, if you have a decorator
then when you say
it’s exactly the same as saying
and your function
fis replaced with the functionwith_logging. Unfortunately, this means that if you then sayit will print
with_loggingbecause that’s the name of your new function. In fact, if you look at the docstring forf, it will be blank becausewith_logginghas no docstring, and so the docstring you wrote won’t be there anymore. Also, if you look at the pydoc result for that function, it won’t be listed as taking one argumentx; instead it’ll be listed as taking*argsand**kwargsbecause that’s what with_logging takes.If using a decorator always meant losing this information about a function, it would be a serious problem. That’s why we have
functools.wraps. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc. And sincewrapsis itself a decorator, the following code does the correct thing: