Python Decorator-打印描述而不是名称

时间:2019-05-28 19:27:43

标签: python python-3.x

我具有以下用于打印响应时间的装饰器功能。用此装饰器装饰另一个函数时,是否可以通过传递装饰器的描述?例如:我想打印“呼叫服务xyz”而不是函数名“ call_service_xyz”

 def timer(func):
        """Print the runtime of the decorated function"""
        @functools.wraps(func)
        def wrapper_timer(*args, **kwargs):
            start_time = time.perf_counter()    # 1
            value = func(*args, **kwargs)
            end_time = time.perf_counter()      # 2
            run_time = end_time - start_time    # 3
            logger.info(f"Finished {func.__name__!r} in {run_time:.4f} secs")
            return value
        return wrapper_timer

@timer("call service xyz")
def call_service_xyz():

1 个答案:

答案 0 :(得分:1)

您可以打印文档字符串作为函数的描述:

db.Subject.aggregate([
    {
        $facet: {
            matched: [ {$match:{"subject.prerequisite":{$gt:6}}} ]
        }
    },
    {
        $project: {
            Total: { $size: "$matched" }
        }
    }
])

或者,如果您希望将描述传递到 def timer(func): """Print the runtime of the decorated function""" @functools.wraps(func) def wrapper_timer(*args, **kwargs): start_time = time.perf_counter() # 1 value = func(*args, **kwargs) end_time = time.perf_counter() # 2 run_time = end_time - start_time # 3 logger.info(f"{desc} Finished in {run_time:.4f} secs") return value return wrapper_timer @timer def call_service_xyz(): """Call service xyz.""" # ^^ this is the docstring which is # assigned to .__doc__ ,则需要为装饰器创建另一个接受参数的层:

timer

现在使用您在问题中描述的方式:

def timer(desc):
    def decorator(func):
        @functools.wraps(func)
        def wrapper_timer(*args, **kw):
            start_time = time.perf_counter()
            value = func(*args, **kw)
            end_time = time.perf_counter()
            run_time = end_time - start_time
            logger.info(f"{func.__doc__!r} Finished in {run_time:.4f} secs")
            return value
        return wrapper_timer
    return decorator