## What is this post about

Many people believe that decorator is one of the obscure concepts in Python.
Trust me, it is not. To be short, a decorator is a function that modifies other
functions via closures.

They are plenty detailed articles about what decorator it is so there is no need to write one more. If you are not familiar with it, you may want to check these:

In this article, I am going to use a simple but interesting example to show

• how to colorize the output in command line
• how to implement a switch case in Python (Python does not have built-in switch case)
• a decorator with parameters

OK, let’s rock.

There is a set of escape sequences used to change the color of texts. So if we want to colorize a sentence, we just need to put the sentence between the color escape sequence and reset escape sequence. For example:

You will see

Chinese New Year

and

Chinese New Year

## How to choose the color in code

As I said, Python does not support switch case. So we cannot switch the color name and choose the corresponding escaped sequence. Fortunately, dictionary would do the work.

The trick is, the dictionary’s built in get method. The first parameter here is key, the second optional parameter is default. As the docstring shows:

D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.

## Use the decorator

Suppose we have a function to implement a task. It may has three kind of return string, if task is completed successfully, it returns “SUCCESS: blah blah …”, if the task is finished but we cannot ensure it’s corretness, it returns “WARNING: blah blah …”, if task failed, returns “ERROR: blah blah …”, how do we colorize these return strings?

As you can tell, to make the decorator with parameters, we need to put it in another decorator.

Decorator are often used as cache, profiler, logger, synchronization(acquire lock, drop lock) and so forth. One of my favourite library Click is also a wonderful example.

Happy Chinese New Year ~