Created
September 25, 2017 18:21
-
-
Save albarralnunez/fe6ee6e87baf34ae4b1364da4d9c5296 to your computer and use it in GitHub Desktop.
Counting inner calls in an unknown function, incorrect code demonstration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
global_counter = 0 | |
def count_calls(func, *args, **kwargs): | |
"""Count calls in function func""" | |
calls = [ -1 ] | |
def tracer(frame, event, arg): | |
global global_counter | |
if event == 'call': | |
global_counter += 1 | |
calls[0] += 1 | |
return tracer | |
sys.settrace(tracer) | |
rv = func(*args, **kwargs) | |
return calls[0], rv | |
def add(a, b): | |
return a + b | |
calls, value = count_calls(add, 1, 1) | |
print('Now after execution of "count_calls" the global attribute "global_counter" should be 1, but is not because we are calling "print" and this is also profiled (i.e. "global_counter": %s), we can see any way that our function is returing the correct number of calls: %s) ' % (global_counter, calls)) | |
global_counter = 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment