Some Python Decorators

I've been learning how to use decorators in Python. As far I understand it a decorator takes as input a function, does something with or to the function and then returns the function. To test out this functionality I've written five examples. First the following preamble is included at the top of the file containing the decorator functions:

countit - will print a line to the terminal every time the function is called with the number of times it has been called.

timeit - times how long a function takes to run and prints this to the terminal.

logit - prints to the the terminal the output that is returned from a function.

beforeit - runs a function that is passed as an argument to the decorator before each function call.

afterit - runs a function that is passed as an argument to the decorator after each function call.

Each of these decorators can be used individually or as a group. For example, this is a function that computes prime numbers in a rather inefficient manner by calculating the factors of each number smaller than it (a better method would be to use the seive of Eratosthenes). It has been decorated with the first three functions above. It is then called three times as follows:

The output produced is:

So whenever I am writing a new python programme I can now import my decorators file and I will have access to the timeit, countit and logit beforit and afterit decorators to aid in debugging.

If you can think of any other useful applications for decorators please let me know in the comments.

Comments