Function call in traceback detection
import inspect | |
import sys | |
def _get_code_id(callable): | |
if inspect.ismethod(callable): | |
return id(callable.im_func.func_code) | |
elif inspect.isfunction(callable): | |
return id(callable.func_code) | |
def function_called_in_traceback(function, traceback): | |
function_code_id = _get_code_id(function) | |
return _code_id_in_traceback(function_code_id, traceback) | |
def _code_id_in_traceback(code_id, traceback): | |
while traceback: | |
if code_id == id(traceback.tb_frame.f_code): | |
return True | |
traceback = traceback.tb_next | |
return False | |
## Example | |
def fail(): | |
1/0 | |
def fail_2(): | |
1/0 | |
try: | |
fail() | |
except Exception: | |
tb1 = sys.exc_info()[2] | |
try: | |
fail_2() | |
except Exception: | |
tb2 = sys.exc_info()[2] | |
assert function_called_in_traceback(fail, tb1) | |
assert not function_called_in_traceback(fail, tb2) | |
assert not function_called_in_traceback(fail_2, tb1) | |
assert function_called_in_traceback(fail_2, tb2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment