Skip to content

Instantly share code, notes, and snippets.

@perrygeo
Created March 20, 2018 20:20
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 perrygeo/a48895c0b551bac0651b53a59234e0bc to your computer and use it in GitHub Desktop.
Save perrygeo/a48895c0b551bac0651b53a59234e0bc to your computer and use it in GitHub Desktop.
Decorator to log all call parameters and return values for a function
import sys
def log_calls(fh=sys.stderr):
"""Logs the function, args, kwargs and return value to a file handle
"""
def decorator(func):
def wrapper(*args, **kwargs):
retval = func(*args, **kwargs)
print(func, args, kwargs, retval, file=fh)
return retval
return wrapper
return decorator
@log_calls()
def add(a, b=1):
return a + b
print(add(2, b=3))
# Will print
# <function add at 0x103ea5950> (2,) {'b': 3} 5
# 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment