Skip to content

Instantly share code, notes, and snippets.

@svrj
Last active May 13, 2022 13:34
Show Gist options
  • Select an option

  • Save svrj/3264103aba9c49049b6266f7d0e5bdab to your computer and use it in GitHub Desktop.

Select an option

Save svrj/3264103aba9c49049b6266f7d0e5bdab to your computer and use it in GitHub Desktop.
Use a decorator to add print/logging statements before invoking classes or functions
import inspect
def logging_decorator(thing):
if isinstance(thing, type):
def inner(*args, **kwargs):
for t in dir(thing):
if not t.startswith("__"):
_thing = getattr(thing, t)
if isinstance(_thing, property):
_thing.fget.__name__ = t
setattr(thing, t, property(logging_decorator(_thing.fget), _thing.fset, _thing.fdel))
elif inspect.ismethod(_thing):
setattr(thing, t, logging_decorator(_thing))
return thing(*args, **kwargs)
else:
def inner(*args, **kwargs):
print(thing.__name__, args, kwargs)
return thing(*args, **kwargs)
return inner
@logging_decorator
class Thing:
def a(self):
print("Hi")
def b(self):
print("Hiii")
@logging_decorator
def func():
print("nothing here")
@logging_decorator
def func2(a):
print(a)
if __name__ == "__main__":
thing = Thing()
thing.a()
thing.b()
func()
func2(1)
@svrj
Copy link
Author

svrj commented May 13, 2022

Thing.a () {}
Hi
Thing.b () {}
Hiii
func () {}
nothing here
func2 (1,) {}
1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment