Thread by Mike Driscoll
- Tweet
- Nov 21, 2022
- #ComputerProgramming #ComputerScience
Thread
One of the harder concepts to learn in #Python are decorators.
So let's take a few moments and learn about them!
๐งต๐๐
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!
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!
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
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:
Here's how you could rewrite the previous example to use the correct syntax:
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! ๐คฏ๐
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!
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/
www.blog.pythonlibrary.org/2017/07/18/python-all-about-decorators/
Thanks so much for reading my series on Python decorators!
Follow me if you're interested in learning more about Python!
Follow me if you're interested in learning more about Python!
Mentions
See All
Akshay ๐ @akshay_pachaar
ยท
Nov 22, 2022
Great thread Mike!!