Thread
One of the harder concepts to learn in #Python are decorators.

So let's take a few moments and learn about them!

๐Ÿงต๐Ÿ๐Ÿ‘‡
It's always good to start with a regular function. Why?

Because you create a decorator using functions!

This function, `doubler()` takes in a number and doubles it. That's it!
But wait! #Python functions are also objects. You can get their `__name__` and their docstring (`__doc__`), if they have one.

You can also get a listing of their other methods with `dir()`

What all this means is that you can pass a function to another function!
Let's create a decorator! A decorator takes in a function as its argument. Its job is to add some information to the function without modifying the function itself.

In this case, you print out the functions name and docstring
That previous example isn't a normal decorator though. The correct method of applying a decorator is with the @ symbol.

Here's how you could rewrite the previous example to use the correct syntax:
Did you know you can stack multiple decorators on a single function?

Here's a silly example:
Did you know you can pass arguments to #Python decorators?

All you need to do is create a function inside a function inside a function! ๐Ÿคฏ๐Ÿ
You can also turn a class into a decorator in #Python!

To make that work, override the `__call__()` method.

I actually like this method a little better for passing arguments to a decorator as the code isn't so crazy-looking!
The examples in this tweet thread are taken from my tutorial, "All About Decorators" on @mousevspython

www.blog.pythonlibrary.org/2017/07/18/python-all-about-decorators/
You can also get these examples on my PyTips repo:

github.com/driscollis/pytips
Thanks so much for reading my series on Python decorators!

Follow me if you're interested in learning more about Python!
Mentions
See All