简体   繁体   中英

How do I count the number of calls of a function in Python 3.6?

I want to count the number of calls of the function f inside of inc . How should I modify the function main to do it?

I have this code:

def inc(f):
    f()
    f()

def main():
    a = 0
    def f():
        a += 1
    inc(f)
    print(a)  # should print 2

main()

But it leads to the error:

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    main()
  File "main.py", line 9, in main
    inc(f)
  File "main.py", line 2, in inc
    f()
  File "main.py", line 8, in f
    a += 1
UnboundLocalError: local variable 'a' referenced before assignment

The usual way is to create an attribute func.invocations for your function func , like

def func(a):
    func.invocations += 1
    return a + 1

func.invocations = 0

and use it like

func(1)    # 2
func(10)   # 11
func.invocations  # 2

To make the whole thing more reusable and readable you can also create a decorator counter that allows you to count the number of calls on any function you like:

import functools

def counter(fn):
    @functools.wraps(fn)
    def helper(*args, **kargs):
        helper.invocations += 1
        return fn(*args, **kargs)
    helper.invocations = 0
    return helper

and then use it like

@counter
def func(a):
    return a + 1

func(1)    # 2
func(10)   # 11
func.invocations # 2
def inc(f):
    f()
    f()

def main():
    a = 0
    def f():
        nonlocal a
        a += 1
    inc(f)
    print(a)  # should print 2

main()

Make a nonlocal in f()

If you are looking for a simple solution, a global variable would do the trick.

reps = 0

def f():
    global reps 
    reps  += 1
    # do your func stuff here

f()
f()
f()
f()  # called f() 4 times
print(reps)  # -> 4

You try this:

def inc(f):    
    f()    
    f() 


def main():    
    a = 0     
    def f():     
        f.counter += 1    
    f.counter =0    
    inc(f)     
    print(f.counter) 


main()

How functions are objects in python you can create an attribute to count the number of call to that function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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