What does functools.wraps do?

前端 未结 6 842
北海茫月
北海茫月 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 07:10

    In short, functools.wraps is just a regular function. Let's consider this official example. With the help of the source code, we can see more details about the implementation and the running steps as follows:

    1. wraps(f) returns an object, say O1. It is an object of the class Partial
    2. The next step is @O1... which is the decorator notation in python. It means

    wrapper=O1.__call__(wrapper)

    Checking the implementation of __call__, we see that after this step, (the left hand side )wrapper becomes the object resulted by self.func(*self.args, *args, **newkeywords) Checking the creation of O1 in __new__, we know self.func is the function update_wrapper. It uses the parameter *args, the right hand side wrapper, as its 1st parameter. Checking the last step of update_wrapper, one can see the right hand side wrapper is returned, with some of attributes modified as needed.

提交回复
热议问题