Reputation: 9745
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
Upvotes: 0
Views: 585
Reputation: 631
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
Upvotes: 0
Reputation: 527
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()
Upvotes: 1
Reputation: 36765
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
Upvotes: 8
Reputation: 15204
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
Upvotes: 0