Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python Decorator Example
#! 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
You can’t perform that action at this time.