Last active
May 13, 2022 13:34
-
-
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
This file contains hidden or 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 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) |
Author
svrj
commented
May 13, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment