Skip to content

Instantly share code, notes, and snippets.

@ppeeou
Created July 11, 2017 00:25
Show Gist options
  • Save ppeeou/cfc989d4dc5863410790e5c0254b65ba to your computer and use it in GitHub Desktop.
Save ppeeou/cfc989d4dc5863410790e5c0254b65ba to your computer and use it in GitHub Desktop.
python decorator ex
# Decorators
def my_logger(orig_func):
import logging
logging.basicConfig(filename='{}.log'.format(orig_func.__name__),level=logging.INFO)
def wrapper(*args,**kwargs):
logging.info(
'Ran with args : {} , and kargs : {}'.format(args,kwargs)
)
return orig_func(*args,**kwargs)
return wrapper
def my_timer(orig_func):
import time
def wrapper(*args,**wargs):
t1 = time.time()
result = orig_func(*args,**wargs)
t2 = time.time() -t1
print '{} ran in {} sec'.format(orig_func.__name__,t2)
return result
return wrapper
def decorator_function(original_function):
def wrapper_function(*args,**kwargs):
print 'wrapper executed this before {}'.format(original_function.__name__)
return original_function(*args,**kwargs)
return wrapper_function
# class decorator_class(object):
# def __init__(self,original_function):
# self.original_function = original_function
# def __call__(self,*args,**kwargs):
# print 'call method this before {}'.format(self.original_function.__name__)
# return self.original_function(*args,**kwargs)
# @decorator_function
# def display() :
# print 'display function ran'
import time
@my_timer
@my_logger
def display_info(name,age):
time.sleep(1)
print 'display_info ran with arguments {} {}'.format(name,age)
# decorator_display = decorator_function(display)
# decorator_display('hi')
# decorator_display('bye')
display_info('John',25)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment