fork download
  1. import functools
  2. import itertools
  3.  
  4. def repr_kwargs(kwargs):
  5. return (f"{key}={repr(value)}" for key, value in kwargs.items())
  6.  
  7. def log_argument_on_exception(func):
  8. """Decorator that logs the argument value if an exception is raised."""
  9.  
  10. @functools.wraps(func)
  11. def wrapper(*args, **kwargs):
  12. try:
  13. return func(*args, **kwargs)
  14. except Exception as e:
  15. all_args = itertools.chain(map(repr, args), repr_kwargs(kwargs))
  16. print(f"{func.__name__}({', '.join(all_args)})")
  17. raise e
  18.  
  19. return wrapper
  20.  
  21. class TestException(Exception):
  22. "Raised for testing purposes"
  23. pass
  24.  
  25.  
  26. @log_argument_on_exception
  27. def foo(a, b):
  28. raise TestException()
  29.  
  30. @log_argument_on_exception
  31. def bar(a, **kwargs):
  32. raise TestException()
  33.  
  34.  
  35. try:
  36. foo(12, "asd")
  37. except TestException:
  38. pass
  39.  
  40. try:
  41. bar(12, b="asd", c=90.23)
  42. except TestException:
  43. pass
  44.  
  45.  
Success #stdin #stdout 0.03s 9568KB
stdin
Standard input is empty
stdout
foo(12, 'asd')
bar(12, b='asd', c=90.23)