top of page
Search
  • Writer's pictureMaia

Python Tips Series: Decorators



The Python decorator concept is something that I had a hard time to wrap my head around. It's considered one of a more advanced programming techniques. And, most of beginners of Python programmers have struggled with it at first. But after we have understood its core concept, it become actually very simple and easy.

Today, I'll explain the very basics of Python decorators, so that every beginners can understand and it will stick with them.


But, first of all, we need to understand a very core concept that every Python developer must know: function.

Let's create a simple function that perform an arithmetic addition of two numbers.

Imagine that we want to develop a functionality that keeps track of how many times a function is being called, for example the 'add()' function above. How would we go about doing that.

Remember that in Python everything are objects, including functions. So, functions can be passed into other functions as parameters.

With that, we can write a function that take the 'add()' function as a param and then count every time the add() function is invoked.

The key here is we reassign the label or name of the 'add' function to whatever the return of the counter() function, so that any call to the add() function after is actually not directly call the original add() function but the "decorated" function that returned from the counter() function.

But it looks very awkward and confusing if we write code like: add = counter(add). And, Python makes it elegant by introducing the decorator syntax as below.

Actually, we can use this decorator syntax to decorate any function we like.

However, if we take a closer look at the decorated function, we can see that it is actually not the original function any more.

The name of the add() function after being decorated is no longer named 'add', but named 'decorate' which is actually the name of the inner function inside the counter() function. And, if we call help() function on the decorated add() function we see something weird too.

To solve these problems, Python has a solution by using the wraps() decorator as below.

Now, we can use decorated function as normal.

And, we don't lose any original metadata of the original function.

That's how Python decorator works under the hood.


Happy decorating!





Recent Posts

See All

Comments


Post: Blog2_Post
bottom of page