Created
January 21, 2019 21:20
-
-
Save JoshZastrow/1e02a18a928daf13b51fe5a51e52538e to your computer and use it in GitHub Desktop.
Decorator
This file contains 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
import functools | |
import os | |
## Example 1: | |
''' | |
Decorator functions are great ways to template-ize a piece of functional | |
code that should be run before / after any other function. For example, | |
checking permissions or connections to a DB could be put into a decorator | |
and reused before all other functions. | |
''' | |
def my_decorator(func): # Consumes a function as the argument | |
@functools.wraps(func) # Always include this with the argument above | |
def additional_function(): | |
print('This is some pre-function code!') # Executes first | |
func() # Always call your function | |
print('This is some post-function code!') | |
return additional_function | |
@my_decorator # syntactic sugar to feed function into decorator function above | |
def my_original_function(): | |
print('This is my original function doing things!') | |
my_original_function() | |
## Example 2: Args for a Decorator | |
os.environ['USER_KEY'] = 1234 | |
def my_decorator_plus_args(num): | |
def my_other_decorator(func): | |
user_key = os.environ['USER_KEY'] | |
@functools.wraps(func) | |
def additional_function(): | |
if num == user_key: | |
func() | |
else: | |
print('USER KEY INCORRECT!!!') | |
return additional_function | |
return my_decorator | |
@my_decorator_plus_args(1111) | |
def my_data_processing_function(): | |
print('Robert); DROP TABLE Students;') | |
my_data_processing_function() | |
# Example 3: Passing Args from Function through Decorator | |
os.environ['USER_KEY'] = 1234 | |
def my_decorator_plus_args(num): | |
def my_other_decorator(func): | |
user_key = os.environ['USER_KEY'] | |
@functools.wraps(func) | |
def decorating_function(*args, **kwargs): # accepts all positional and keywords coming in (i.e. def fun(4, 5, eye='brown')) | |
if num == user_key: | |
print('decorator doing its duty') | |
func(*args, **kwargs) | |
print('function ran') | |
else: | |
print('USER KEY INCORRECT!!!') | |
return additional_function | |
return my_decorator | |
@my_decorator_plus_args(1234) | |
def basic_function_with_args(height, weight): | |
print('my height: {}\nmy weight: {}'.format(height, weight)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment