Created
March 14, 2019 19:40
-
-
Save craigderington/5d274ef135a6a09732f54d1eea04e469 to your computer and use it in GitHub Desktop.
Python Decorator Example
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
#! usr/bin/python3.6 | |
# coding: utf-8 | |
import time | |
from functools import wraps | |
def my_logger(func): | |
import logging | |
logging.basicConfig(filename='{}.log'.format(str(func.__name__)), level=logging.DEBUG) | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
logging.debug('Ran {} with args {} and kwargs {}.'.format((str(func.__name__)), args, kwargs)) | |
return func(*args, **kwargs) | |
return wrapper | |
def my_timer(func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
t1 = time.time() | |
result = func(*args, **kwargs) | |
t2 = time.time() - t1 | |
print('{} ran in {} seconds.'.format(str(func.__name__), str(t2))) | |
return result | |
return wrapper | |
@my_logger | |
def display_func(name, age, number): | |
time.sleep(0.15) | |
print('Executing the display function...') | |
@my_timer | |
def display_timer(): | |
time.sleep(0.558) | |
print('Executing display timer function...') | |
if __name__ == '__main__': | |
display_func('James', 55, '555-1212') | |
display_timer() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment