Mike Driscoll Profile picture
I tweet about everything #Python Writing about Python @mousevspython @realpython Teaching at @TeachMePy Author of multiple books - https://t.co/MdP25zw5zQ

Nov 12, 2021, 11 tweets

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

blog.pythonlibrary.org/2017/07/18/pytโ€ฆ

You can also get these examples on my PyTips repo:

github.com/driscollis/pytโ€ฆ

Thanks so much for reading my series on Python decorators!

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

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling