Skip to content

Instantly share code, notes, and snippets.

@typoman
Created June 10, 2025 14:37
Show Gist options
  • Save typoman/5dc6a7ab36ebbe75976a71f24afa4821 to your computer and use it in GitHub Desktop.
Save typoman/5dc6a7ab36ebbe75976a71f24afa4821 to your computer and use it in GitHub Desktop.
A python decodator for creating samples for doctests right from the function calls
import inspect
def debug_decorator(func):
"""A decorator that if written behind a function, it prints the function
call and the return value. It's mainly useful for debugging and adding the
test functions calls to the function doctest.
Example:
>>> @debug_decorator
... def my_function(a, b, c=10):
... return a + b + c
...
>>> my_function(1, 2)
>>> my_function(1, 2, c=5)
>>> my_function(a=5, b=3)
Output:
>>> my_function(a=1, b=2, c=10)
13
<BLANKLINE>
>>> my_function(a=1, b=2, c=5)
8
<BLANKLINE>
>>> my_function(a=5, b=3, c=10)
18
<BLANKLINE>
"""
def wrapper(*args, **kwargs):
sig = inspect.signature(func)
bound_args = sig.bind(*args, **kwargs)
bound_args.apply_defaults()
args_repr = [f"{name}={repr(value)}" for name, value in bound_args.arguments.items()]
print(f">>> {func.__name__}({', '.join(args_repr)})")
result = func(*args, **kwargs)
print(repr(result))
print()
return result
return wrapper
# --- Example Usage ---
@debug_decorator
def my_function(a, b, c=10):
return a + b + c
my_function(1, 2)
my_function(1, 2, c=5)
my_function(a=5, b=3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment