Created
March 20, 2018 20:20
-
-
Save perrygeo/a48895c0b551bac0651b53a59234e0bc to your computer and use it in GitHub Desktop.
Decorator to log all call parameters and return values for a function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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