获取装饰功能的名称?

时间:2011-02-03 14:03:55

标签: python django decorator

这是我的装饰者:

def check_domain(func):

    def wrapper(domain_id, *args, **kwargs):
        domain = get_object_or_None(Domain, id=domain_id)
        if not domain:
            return None
        return func(domain_id, *args, **kwargs)

    return wrapper

这是一个包装函数:

@check_domain
def collect_data(domain_id, from_date, to_date):
    do_stuff(...)

如果我collect_data.__name__,我会wrapper而不是collect_data

有什么想法吗?

6 个答案:

答案 0 :(得分:35)

不需要functools.wraps!只需使用method.__name__

即可
import time

def timeit(method):
    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()
        print('Function', method.__name__, 'time:', round((te -ts)*1000,1), 'ms')
        print()
        return result
    return timed

@timeit
def math_harder():
    [x**(x%17)^x%17 for x in range(1,5555)]
math_harder()

@timeit
def sleeper_agent():
    time.sleep(1)
sleeper_agent()

输出:

Function math_harder time: 8.4 ms
Function sleeper_agent time: 1003.7 ms

答案 1 :(得分:14)

您可能希望使用functools中的wraps

有一个明显的例子似乎适合你:)

答案 2 :(得分:4)

除了functools.wraps之外,您还可以查看旨在帮助解决此问题的decorator模块。

答案 3 :(得分:3)

结帐functools.wraps。但是,如果这是一个问题,则需要python 2.5或更高版本。

答案 4 :(得分:2)

答案 5 :(得分:0)

对于需要在有多个装饰器时访问装饰函数名称的人,如下所示:

@decorator1
@decorator2
@decorator3
def decorated_func(stuff):
    return stuff

上面提到的functools.wraps解决了这个问题。