Python Decorator Revisited, Part 1: What is a decorator?

I love programming in Python. It not only keeps lines of code to the minimum but also has great language features that allow developers to think about programming in different ways. I often get confused whether Python is a object-oriented language or a funcitonal programming language (to clarify, it is a general-purpose programming language). It even has lambda functions!! However, the one language feature that I like the most is decorator. Decorator is simply a syntatic sugar that looks like Java’s annotation. This is a simple example of decorator in Python:

@decorator
def decorated_func():
... some code ...

Same as . . .

def decorated_func():
... some code ...

decorated_func = decorator(decorated
_func)

Basically, decorator is a function that can do anything before and after a decorated_func gets called. This is closely related to the decorator design pattern, which dynamically add functionality or responsibility to an existing object. With that said, you can add as many decorators as you can as long as their types are matched:

@decorator1
@decorator2
@decorator3
def decorated_func():
     ... some code ....

In the next two posts, I will go over how to create a decorator for general functions and classes. I will also go over some interesting ways of using decorators, such as the famous memoized decorator.