简体   繁体   English

Python-计算函数通过装饰器的次数

[英]Python - Count number of times function passes through decorator

I have a decorator that I wanna make increase a counter anytime a function is routed through the decorator. 我有一个装饰器,只要通过装饰器路由一个函数,我都想增加一个计数器。 So far this is my code 到目前为止,这是我的代码

from functools import wraps
def count_check(function):
    """Returns number of times any function with this decorator is called
    """
    count = []
    @wraps(function)
    def increase_count(*args, **kwargs):
        count.append(1)
        return function(*args, **kwargs), len(count)

    return increase_count

It works fine, until another function passes through the decorator and count resets to 0 for that function. 它可以正常工作,直到另一个功能通过装饰器并将该功能的计数重置为0为止。 How can I aggregate the total number of times? 如何汇总总次数?

This should do it: 应该这样做:

from functools import wraps
def count_check(function, count=[0]):
    """Returns number of times any function with this decorator is called
    """
    @wraps(function)
    def increase_count(*args, **kwargs):
        count[0] += 1
        return function(*args, **kwargs), count[0]

    return increase_count

You could also get fancy and use a dictionary counting the functions individually as well as separately: 您也可能会喜欢上字典,并使用字典分别对函数进行计数:

from functools import wraps
def count_check(function, count={}):
    """Returns number of times any function with this decorator is called
    """
    count[function] = 0
    @wraps(function)
    def increase_count(*args, **kwargs):
        count[function] += 1
        return function(*args, **kwargs), count[function], sum(count.values())

    return increase_count

Demo: 演示:

@count_check
def foo():
    return 42

print(foo(), foo(), foo())

@count_check
def bar():
    return 23

print(bar(), bar(), bar())
print(foo(), foo(), foo())

Prints: 打印:

(42, 1, 1) (42, 2, 2) (42, 3, 3)
(23, 1, 4) (23, 2, 5) (23, 3, 6)
(42, 4, 7) (42, 5, 8) (42, 6, 9)

I would try something like: 我会尝试类似的东西:

from functools import wraps
count = 0
def count_check(function):
    @wraps(function)
    def increase_count(*args, **kwargs):
        global count
        count += 1
        return function(*args, **kwargs), count

    return increase_count

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM