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
Want to create a copy of a #Python list? Use Python's `copy()` method!
Note: Watch out if your list contains lists of dictionaries. In those cases, you might be better off using copy.deepcopy()
But be careful! If your list contains a mutable object, like another list or a dictionary, you may encounter some unexpected behavior.
In the following example, you `copy()` the list. Then you modify the nested dictionary in the copy, but that also changes the original list!
You can fix this behavior by using Python's `copy` module. It provides a deepcopy() function that you can use which will make a deep copy of the ENTIRE list!