Skip to content

Instantly share code, notes, and snippets.

@juancarlospaco
Created August 9, 2023 12:58
Show Gist options
  • Save juancarlospaco/270e75291c0d31af0afbf43955aa9149 to your computer and use it in GitHub Desktop.
Save juancarlospaco/270e75291c0d31af0afbf43955aa9149 to your computer and use it in GitHub Desktop.
debugutils
## Debug utilities, to keep it simple and stdlib-only.
import functools
__all__ = ("debugs", )
def debugs(func):
func.__indent__ = 0
def __args_to_str(*args):
# Arguments to string.
result = ", ".join(map(str, args))
return result
def __kwargs_to_str(**kwargs):
# kwargs to string.
result = ""
for k, v in kwargs.items():
result += f"{k}={v},"
return result[:-1]
@functools.wraps(func)
def wrapper_logging(*args, **kwargs):
# Handle indentation.
func_indent = " " * func.__indent__
func.__indent__ += 2
# Friendly names.
func_name = func.__qualname__
func_args = __args_to_str(*args)
func_kwargs = __kwargs_to_str(**kwargs)
# Enter func.
print(f"{func_indent}➡️\t{func_name}({func_args}", end="")
# Actual debugging parts.
if func_kwargs != "":
print(f", {func_kwargs}", end="")
print(")")
# Pass thru...
result = func(*args, **kwargs)
# Leave func.
print(f"{func_indent}⬅️\t{func_name}({result})")
return result
return wrapper_logging
if __name__ == '__main__':
# This is just a self-testing/sanity-check,
# not meant to be used directly, run it as an example usage.
@debugs
def example(n):
if n == 1:
return 1
else:
return n * example(n - 1)
result = example(3)
print(f"{result=}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment