2017-09-27 15 views
1

デコレータfunctools.wrap呼び出し方法functools.update_wrapperなぜ `update_wrapper`の代わりに` wrap`をデコレータとして使うのですか?

update_wrapperの代わりにwrapを使用する必要があることをご理解ください。 wrapの代わりにupdate_wrapperをデコレータとして使用できないのはなぜですか?例えば

from functools import update_wrapper 
def wrap1(func): 
    def call_it(*args, **kwargs): 
     """wrap func: call_it1""" 
     print('before call in call_it1') 
     return func(*args, **kwargs) 
    return update_wrapper(call_it, func) 

@wrap1 
def hello1(): 
    """test hello 1""" 
    print('hello world1') 

hello1() 

def wrap3(func): 
    @wraps(func) 
    def call_it(*args, **kwargs): 
     """wrap func: call_it3""" 
     print('before call in call_it3') 
     return func(*args, **kwargs) 
    return call_it 

@wrap3 
def hello3(): 
    """test hello 3""" 
    print('hello world3') 

hello3()  

作品。しかし、なぜ以下のことはしないのですか?エラー

TypeError: update_wrapper() missing 1 required positional argument: 'wrapper' 

The declarations of wraps and update_wrapper

def wrap2(func): 
    @update_wrapper(wrapped=func) # error, see below 
    def call_it(*args, **kwargs): 
     """wrap func: call_it2""" 
     print('before call in call_it2') 
     return func(*args, **kwargs) 
    return call_it 

@wrap2 
def hello2(): 
    """test hello 2""" 
    print('hello world2') 

hello2() 

ある:

@functools.wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) 

functools.update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) 

位置引数wrapperがの最初の引数であります、 なぜ次のようなものがcall_itとしての引数としてwrapperになるのでしょうか?

@update_wrapper(wrapped=func) 
def call_it(*args, **kwargs): 

代わりwrapを使用してのデコレータとしてupdate_wrapperを使用するために、いくつかの方法はありますか?デコレータとして@を使用して

答えて

1

は、基本的には、これに沸く:今、私たちはあなたのケースにそれを適用した場合

def f(...): 
    ... 

f = (value)(f) 

@(value) 
def f(...): 
    ... 

は同じなので

@update_wrapper(wrapped=func) 
def call_it(*args, **kwargs): 
    ... 
def call_it(*args, **kwargs): 
    ... 

call_it = update_wrapper(wrapped=func)(call_it) 

ここで問題となるのは、最初に2番目の引数でのみ呼び出されるということです。その後、すぐにエラーが発生します。

update_wrapperはデコレータとして使用するようには設計されていませんが、wrapsはデコレータ(工場)です。

関連する問題