Skip to content

Instantly share code, notes, and snippets.

@wiccy46
Created April 28, 2020 05:42
Show Gist options
  • Save wiccy46/dceb7de6a1854aad98d7081458643924 to your computer and use it in GitHub Desktop.
Save wiccy46/dceb7de6a1854aad98d7081458643924 to your computer and use it in GitHub Desktop.
[decorator]Python decorator #python
# Use decorator to do something before or after certain function
# E.g. Timer and Certain error check
# importing time module
from time import time
class Timer:
def __init__(self, func):
self.function = func
def __call__(self, *args, **kwargs):
start_time = time()
result = self.function(*args, **kwargs)
end_time = time()
print("Execution took {} seconds".format(end_time-start_time))
return result
# adding a decorator to the function
@Timer
def some_function(delay):
from time import sleep
# Introducing some time delay to
# simulate a time taking function.
sleep(delay)
some_function(3)
# class decorator
class ErrorCheck:
def __init__(self, function):
self.function = function
def __call__(self, *params):
if any([isinstance(i, str) for i in params]):
raise TypeError("parameter cannot be a string !!")
else:
return self.function(*params)
@ErrorCheck
def add_numbers(*numbers):
return sum(numbers)
# returns 6
print(add_numbers(1, 2, 3))
# raises Error.
print(add_numbers(1, '2', 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment