Skip to content

Instantly share code, notes, and snippets.

@Lothiraldan
Created April 11, 2015 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lothiraldan/7c295329e7ec4a04d423 to your computer and use it in GitHub Desktop.
Save Lothiraldan/7c295329e7ec4a04d423 to your computer and use it in GitHub Desktop.
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