Last active
October 23, 2019 15:43
-
-
Save charlesreid1/906b68052d08664b692c6889ccd6d05f to your computer and use it in GitHub Desktop.
Examples of Python decorators in action
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 random | |
""" | |
Python Decorators: Some Examples | |
This file contains a few examples of ways you can | |
use decorators. These are minimal examples that | |
should generalize usefully in many situations. | |
Also see: https://wiki.python.org/moin/PythonDecoratorLibrary | |
""" | |
# Example: | |
# Duplicate a call to a function. | |
# Rather than actually performing an action | |
# (like calling the function passed in), | |
# create a new function that carries out | |
# the sequences of actions desired. | |
# | |
# The decorated function should perform an | |
# action (no return value). The next example | |
# covers functions with return values. | |
def duplicate_call(f): | |
def g(*args,**kwargs): | |
f(*args,**kwargs) | |
f(*args,**kwargs) | |
return g | |
@duplicate_call | |
def square(arg): | |
print(arg*arg) | |
# Example: | |
# If we want to perform the action above | |
# (i.e., duplicate the function results), | |
# but the decorated function has a return | |
# value, we can compose the return values | |
# in the new function. | |
def triplicate(f): | |
def g(*args,**kwargs): | |
return (f(*args,**kwargs),f(*args,**kwargs),f(*args,**kwargs)) | |
return g | |
@triplicate | |
def cube(arg): | |
return arg*arg*arg | |
# Example: | |
# Modify the return value of a function. | |
# Given an input function that returns integers, | |
# this decorator makes sure the input function | |
# never returns an integer larger than 10. | |
def volkswagen(f): | |
def g(*args, **kwargs): | |
return min(10, f(*args,**kwargs)) | |
return g | |
@volkswagen | |
def emissions_test(): | |
return random.randint(1,100) | |
if __name__=="__main__": | |
square(5) | |
# output: | |
# 25 | |
# 25 | |
print(cube(5)) | |
# output: | |
# (125, 125, 125) | |
print("Emissions test result: %d"%(emissions_test())) | |
# output: | |
# Emissions test result: 9 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment