Skip to content

Instantly share code, notes, and snippets.

@Highstaker
Last active May 18, 2016 18:03
Show Gist options
  • Save Highstaker/0977bcb0e784c8787f7eed11326c4979 to your computer and use it in GitHub Desktop.
Save Highstaker/0977bcb0e784c8787f7eed11326c4979 to your computer and use it in GitHub Desktop.
Simple decorator examples
import time
import functools
def timer(func):
#Decorator function takes the decorated function as parameter
@functools.wraps(func)
def wrapper(*args, **kwargs):
#the replacement function to be used
#Here we do stuff that is necessary before the function is run
start_time = time.time()
# Running the actual function and storing the result
result = func(*args, **kwargs)
# Doing stuff after function
elapsed_time = time.time() - start_time
print("Time taken to run {0}: {1} seconds".format(func.__name__,elapsed_time ))
#return the result of a function
return result
# return the replacement function
return wrapper
@timer
def foo(range_end):
"""
A test function that returns a list of integers from 0 to range_end.
"""
return [i for i in range(range_end)]
foo(10**5)
# if I hadn't used @functools.wraps(func) decorator for the wrapper,
# these calls would have returned "wrapper" and no docstring instead of `foo` and its docstring.
print(foo.__name__)
print(foo.__doc__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment