Skip to content

Instantly share code, notes, and snippets.

@LucK1Y
Last active December 14, 2022 12:18
Show Gist options
  • Save LucK1Y/43bbb727192f97752362330defd6ec46 to your computer and use it in GitHub Desktop.
Save LucK1Y/43bbb727192f97752362330defd6ec46 to your computer and use it in GitHub Desktop.
useful python decorators
from time import time
from typing import Callable
def catch_exc_decor(exc_val):
def inner_decor(func: [Callable]):
def inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as ex:
print(f"[X] Caught {ex} in {func.__name__}. Will return ")
return exc_val
return inner
return inner_decor
def timer_func(func):
# This function shows the execution time of
# the function object passed
def wrap_func(*args, **kwargs):
t1 = time()
result = func(*args, **kwargs)
t2 = time()
print(f'Function {func.__name__!r} executed in {(t2 - t1):.4f}s')
return result
return wrap_func
# usage
@timer_func
@catch_exc_decor(exc_val = "Message when error is thrown")
def foo() -> str:
return "no error"
@timer_func
@catch_exc_decor(exc_val = "Message when error is thrown")
def foo2() -> str:
raise Exception("error")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment