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

0

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

  

This is a convenience function for invoking update_wrapper() as a   function decorator when defining a wrapper function. It is equivalent   to partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated) .

I know that the update_wrapper function is internally called by wraps , I would like an example where you need to use the update_wrapper function and not wraps .

    
asked by anonymous 28.10.2018 / 02:25

1 answer

2

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

While the wraps function does nothing, it 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 destination 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 syntax of decorator @ does is to call the function passing the other as a parameter:

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

This allows you to define the function and "wrappar" it directly, in a command-only sequence.

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

    
29.10.2018 / 21:55