Skip to content

Instantly share code, notes, and snippets.

@bricef
Created January 18, 2020 07:17
Show Gist options
  • Save bricef/e23e4cb1bdb35c34eed6b27bc06ad120 to your computer and use it in GitHub Desktop.
Save bricef/e23e4cb1bdb35c34eed6b27bc06ad120 to your computer and use it in GitHub Desktop.
Call tracing decorator
class TraceCalls(object):
""" Use as a decorator on functions that should be traced. Several
functions can be decorated - they will all be indented according
to their call depth.
source: https://eli.thegreenplace.net/2012/08/22/easy-tracing-of-nested-function-calls-in-python
"""
def __init__(self, stream=sys.stdout, indent_step=2, show_ret=False):
self.stream = stream
self.indent_step = indent_step
self.show_ret = show_ret
# This is a class attribute since we want to share the indentation
# level between different traced functions, in case they call
# each other.
TraceCalls.cur_indent = 0
def __call__(self, fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if not config.get("debug", False):
# short circuit in case we are not in verbose mode.
return fn(*args, **kwargs)
indent = ' ' * TraceCalls.cur_indent
argstr = ', '.join(
[repr(a) for a in args] +
["%s=%s" % (a, repr(b)) for a, b in kwargs.items()])
self.stream.write('%s%s(%s)\n' % (indent, fn.__name__, argstr))
TraceCalls.cur_indent += self.indent_step
ret = fn(*args, **kwargs)
TraceCalls.cur_indent -= self.indent_step
if self.show_ret:
self.stream.write('%s--> %s\n' % (indent, ret))
return ret
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment