In some cases, we can extract a common aspect from a number of functions. Concerns like security, audit, or logging are common examples of something we might want to implement consistently across many functions or classes.
Let's look at a way to support enhanced debugging. Our goal is to have a simple annotation that we can use to provide consistent, detailed output from several unrelated functions. We'd like to create a module with definitions like this:
@debug_log def some_function(ksloc): return 2.4*ksloc**1.05 @debug_log def another_function(ksloc, a=3.6, b=1.20): return a*ksloc**b
We've defined two simple functions that will be wrapped by a decorator to provide consistent debugging output.
A decorator is a function that accepts a function as an argument and returns a function as a result. What we've shown in the preceding piece of code is evaluated as follows:
>>> def some_function(ksloc): ... return 2.4*ksloc**1.05 >>> some_function...