What is the difference between the wraps and update_wrapper functions of the funtools module

Asked

Viewed 58 times

0

In the module functools of bibliotaca padrão of Python there are two functions update_wrapper and wraps in the documentation of the function wraps we have:

This is a convenience Function for invoking update_wrapper() as to Function Decorator when Defining a wrapper Function. It is equivalent to partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated).

I know the function update_wrapper is called internally by wraps, would like an example where it is necessary to use the function update_wrapper and not of wraps.

  • Related question in the Soen

  • The @nosklo reply explains well. update_wrapper() does all the magic and wraps() serves to use update_wrapper as Decorator.

1 answer

2


In fact of the two functions, the only one that does anything is the update_wrapper. She copies, among other things, __module__, __name__, __qualname__, __annotations__ and __doc__ from one function to another.

Already the function wraps does nothing to itself, simply calls the update_wrapper. What changes are the parameters... For the first function, you have to pass the two functions as parameter at the same time, the source and the target of the copy:

resultado = update_wrapper(x, y) # copia de y para x

Already for the second you have to pass the parameters separately:

tmp = wraps(y)
tmp(x)      #copia de y pra x

or

wraps(y)(x)  #copia de y pra x

The reason is to facilitate the use as decorator, after all, what the decorator syntax @ is to call the function by passing the other as parameter:

@wraps(y)
def x(...):
    ....

This allows you to define the function and "wrapper" it directly, in a single sequence of commands.

SUMMING UP, wraps is a convenience function that calls update_wrapper for you in a way that makes it easier to use it as a decorator.

  • Thanks again for the reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.