python_decorators.html


001| """Python Decorator Functions.
001| 
001| Decorator functions can be used to "wrap" other functions, allowing access
001| to those other functions' input parameters and return values. Because Python
001| is very self-reflective, decorator functions can access other aspects of the
001| functions they wrap.
001| 
001| Decorators functions typically have a single argument, a function, and they
001| also return a function. Usually the returned function is a proxy for the
001| input function and generally calls it.
001| 
001| The general format of a decorator is:
001| 
001| def decorator_function (input_function):
001|     #
001|     # (access to input_function)
001|     #
001|     def proxy_function (input_parameters):
001|         #
001|         # (access to input_parameters)
001|         #
001|         retval = input_function(input_parameters)
001|         #
001|         # (access to return value)
001|         #
001|         return retval
001| 
001|     # Return the wrapper function...
001|     return proxy_function
001| 
001| Use this decorator function to decorate any function:
001| 
001| @decorator_function
001| def my_function_to_decorate (input_params):
001|     ...
001|     ...
001|     ...
001|     return some_value
001| 
001| """

002| import time
003| import random
004| 
005| 
006| def timer (function):
007|     '''Decorator function for timing other functions.'''
008| 
009|     # Create a (new) empty list to store timings in...
010|     ts = []
011| 
012|     def wrapper (*args):
013|         '''Proxy function that wraps other functions.'''
014|         t0 = time.time()
015| 
016|         # Call the wrapped function...
017|         rv = function(*args)
018| 
019|         # Determine how long we were in the function...
020|         tt = time.time() - t0
021|         # And add the result to the list of timings...
022|         ts.append(tt)
023| 
024|         # Return what the function returned...
025|         return rv
026| 
027|     # Assign the timings list to this wrapper...
028|     wrapper.times = ts
029|     # Note: Above is same as: setattr(wrapper, 'times', ts)
030| 
031|     # Return the wrapper function...
032|     return wrapper
033| 
034| 
035| @timer
036| def my_function (x, y, z):
037|     ...
038|     ...
039|     time.sleep(1.5 + (random.random() * 5))
040|     ...
041|     ...
042|     return
043| 
044| @timer
045| def my_other_function (a, b, c, d):
046|     ...
047|     ...
048|     time.sleep(0.5 + (random.random() * 12))
049|     ...
050|     ...
051|     return
052| 
053| 
054| 
055| def main ():
056|     """Main function."""
057| 
058|     print('Calling my_function()...')
059|     for ix in range(8):
060|         print(ix+1, '...', sep='', end=' ')
061|         my_function(21, 42, 63)
062|     print()
063|     print()
064| 
065|     print('Calling my_other_function()...')
066|     for ix in range(8):
067|         print(ix+1, '...', sep='', end=' ')
068|         my_other_function(1.61, 2.7, 3.1415, 5.0505)
069|     print()
070|     print()
071| 
072|     # Display timings for both functions...
073|     print(f'Times for my_function() [{len(my_function.times)} calls]:')
074|     print(f'Total: {sum(my_function.times)}')
075|     print(f'Max: {max(my_function.times)}')
076|     print(f'Min: {min(my_function.times)}')
077|     print()
078|     for ix,t in enumerate(my_function.times):
079|         print(f'[{ix:2d}] {t:9.6f}')
080|     print()
081| 
082|     print(f'Times for my_other_function() [{len(my_other_function.times)} calls]:')
083|     print(f'Total Time: {sum(my_other_function.times)}')
084|     print(f'Max Time: {max(my_other_function.times)}')
085|     print(f'Min Time: {min(my_other_function.times)}')
086|     print()
087|     for ix,t in enumerate(my_other_function.times):
088|         print(f'[{ix:2d}] {t:9.6f}')
089|     print()
090|     print()
091| 
092| 
093| if __name__ == "__main__":
094|     print()
095|     main()
096|     print()
097| """eof"""
098|