簡體   English   中英

帶裝飾函數參數的python decorator

[英]python decorator with arguments of decorated function

當我用@包裝函數時,如何使包裝函數的外觀和感覺完全像包裝函數一樣? 特別是help(function)

一些代碼:

>>> def wraps(f):
    def call(*args, **kw):
        print('in', f, args, kw) # example code. I need to transfer the arguments to another process and pickle them.
        return f(*args, **kw)
    return call

>>> def g():pass

>>> @wraps
def f(a, b = 1, g = g, *args, **kw):
    pass

>>> help(f)
Help on function call in module __main__:

call(*args, **kw) # this line bothers me. It should look different, look below

>>> def f(a, b = 1, g = g, *args, **kw):
    pass

>>> help(f)
Help on function f in module __main__:

f(a, b=1, g=<function g at 0x02EE14B0>, *args, **kw) # help(f) should look like this.

動機:當我輸入幫助窗口,當我輸入f( * plopp *我看到(a, b = 1, g = g, *args, **kw)時,看到參數也會很高興。(在此IDLE Python Shell中的case

我看了一下inspect模塊,它幫助我進行了很好的格式化。 問題仍然存在:我如何用參數做到這一點..

def f(d = {}):一樣傳遞的默認可變參數def f(d = {}):不需要工作,因為我將參數傳遞給另一個進程,無論如何身份都會丟失。

functools.wraps可用於復制函數的名稱和docstring。 從頭開始復制原始功能簽名要困難得多。

但是,如果您使用第三方裝飾器模塊

import decorator


@decorator.decorator
def wraps(f):
    def call(*args, **kw):
        print('in', f, args, kw) 
        return f(*args, **kw)
    return call


def g():pass

@wraps
def f(a, b = 1, g = g, *args, **kw):
    pass

help(f)

產量

Help on function f in module __main__:

f(a, b=1, g=<function g>, *args, **kw)

使用functools.wraps

from functools import wraps

def wrapper(f):
    @wraps(f)
    def call(*args, **kw):
        print('in', f, args, kw)
        return f(*args, **kw)
    return call

@wrapper
def f(a, b = 1, g = g, *args, **kw):
    pass

help(f)
Help on function f in module __main__:

f(a, b=1, g=<function g at 0x7f5ad14a6048>, *args, **kw)

這會保留包裝函數的__name____doc__屬性。

我認為其他答案更可取,但如果由於某種原因您不想使用外部模塊,您可以隨時更改裝飾器:

def wraps(f):
  def call(*args, **kw):
    print('in', f, args, kw)
    return f(*args, **kw)
call.__name__ = f.__name__
call.__doc__ = f.__doc__
return call

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM