-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathcount_calls.py
More file actions
47 lines (34 loc) · 956 Bytes
/
Copy pathcount_calls.py
File metadata and controls
47 lines (34 loc) · 956 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
'''
Defines the `count_calls` decorator.
See its documentation for more details.
'''
from python_toolbox.third_party.decorator import decorator
def count_calls(function):
'''
Decorator for counting the calls made to a function.
The number of calls is available in the decorated function's `.call_count`
attribute.
Example usage:
>>> @count_calls
... def f(x):
... return x*x
...
>>> f(3)
9
>>> f(6)
36
>>> f.call_count
2
>>> f(9)
81
>>> f.call_count
3
'''
def _count_calls(function, *args, **kwargs):
decorated_function.call_count += 1
return function(*args, **kwargs)
decorated_function = decorator(_count_calls, function)
decorated_function.call_count = 0
return decorated_function