Python -decorators…
Decorators can be thought of as functions which modify the functionality of another function. They help to make your code shorter and more “Pythonic”. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it.
Refresher:
In Python, functions are first class objects that means that functions in Python can be used or passed as arguments. Here is a tutorial on first class functions to sharpen that brain power First Class Functions.
Remember:
- A function is an instance of the Object type.
- You can store the function in a variable.
- You can pass the function as a parameter to another function.
- You can return the function from a function.
- You can store them in data structures such as hash tables, lists, …
Why Use A Decorator?
Imagine walking into work and being told that those TPS reports need to have an input/output logging on each step in the report generator….and they need them in three days time to submit.
Without decorators you could spend days finding all the functions in the reports and then adding a manual logging call to each one.
OR
You can be done in couple lines of code, by adding a decorator in front of each function definition.
Decorators:
In Decorators, functions are taken as the argument into another function and then called inside the wrapper function.
Simple decorator example —
When we call say_hello() we get the following:
The above example works but could be cleaner, time for some syntax sugar. Python allows you to use the @ syntax to decorate a function. This decorates the function immediately at definition, so you may choose to decorate some functions manually in order to be able to recall the undecorated function.
So what just happened here? A decorator simply wrapped the function and modified its behavior.
Some Takeaways
- Decorators are completely reusable. You can reuse a decorator by creating a file, decorators.py and perform a regular import to use.
- Decorators define reusable building blocks you can apply to a callable to modify its behavior without permanently modifying the callable itself.
- The
@
syntax is just a shorthand for calling the decorator on an input function.
For more information on Python decorators visit Python.org