What does functools.wraps do?

前端 未结 6 841
北海茫月
北海茫月 2020-11-22 06:23

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 ther

6条回答
  •  遇见更好的自我
    2020-11-22 06:47

    1. Prerequisite: You must know how to use decorators and specially with wraps. This comment explains it a bit clear or this link also explains it pretty well.

    2. Whenever we use For eg: @wraps followed by our own wrapper function. As per the details given in this link , it says that

    functools.wraps is 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).

    So @wraps decorator actually gives a call to functools.partial(func[,*args][, **keywords]).

    The functools.partial() definition says that

    The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature. For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two:

    >>> from functools import partial
    >>> basetwo = partial(int, base=2)
    >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
    >>> basetwo('10010')
    18
    

    Which brings me to the conclusion that, @wraps gives a call to partial() and it passes your wrapper function as a parameter to it. The partial() in the end returns the simplified version i.e the object of what's inside the wrapper function and not the wrapper function itself.

提交回复
热议问题