easy_decorator

Run Settings
LanguagePython
Language Version
Run Command
# -*- coding: utf-8 -*- def my_decorator(func): print 'test before' def wrapper(*args, **kwargs): print("Before call") result = func(*args, **kwargs) print("After call") return result print 'test afterwards' return wrapper @my_decorator def add(a, b): return a + b add(1, 3)
# -*- coding: utf-8 -*- ''' Classes can also be a decorator ''' class logit(object): def __init__(self, file="log.txt"): self.log_file = file def __call__(self): log_string = func.__name__ + " was called" print(log_string) # Open the logfile and append with open(self.logfile, 'a') as opened_file: # Now we log to the specified logfile opened_file.write(log_string + '\n') # Now, send a notification self.notify() def notify(self): # logit only logs, no more pass
# -*- coding: utf-8 -*- ''' functools offers a decorator 'wraps()' Note: @wraps takes a function to be decorated and adds the functionality of copying over the function name, docstring, arguments list, etc. ''' from functools import wraps def a_new_decorator(a_func): @wraps(a_func) def wrapTheFunction(): print("I am doing some boring work before executing a_func()") a_func() print("I am doing some boring work after executing a_func()") return wrapTheFunction @a_new_decorator def a_function_requiring_decoration(): """Hey yo! Decorate me!""" print "I am the function which needs some decoration to remove my foul smell" print(a_function_requiring_decoration.__name__) # Output: a_function_requiring_decoration
from functools import wraps def decorator_name(f): @wraps(f) def decorated(*args, **kwargs): if not can_run: return "Function will not run" return f(*args, **kwargs) return decorated @decorator_name def func(): return("Function is running") can_run = True print(func()) # Output: Function is running can_run = False print(func()) # Output: Function will not run
Editor Settings
Theme
Key bindings
Full width
Lines