Mastering Python: Part 3: Decorators

Learning Python

Using Python

Mastering Python

Python is a general-purpose interpreted programming language. It emphasizes readability through the use of whitespace and supports multiple programming paradigms such as functional and object-oriented models.


Decorators

Over time, languages have a way of organizing themselves through usage and community standards. In Python, decorators are a form of this.

It is possible to write a function that takes a function as an argument that changes how it (the original function) functions. If this seems confusing, that is why decorators are used in Python.

Wrapping Functions

In their original form, decorated functions are changed through being wrapped by other functions. They are called (the original) as a result of some other function being first called.

This is very helpful in situations where some functions are known and a particular response is wanted. Decorated functions can be thought of as existing “routes” where new parts can be added through “wrapping” new functions.

The @ Shorthand

To help with the function wrapping and overriding code lines, there is an @ symbol. This is a decorator.

This simplifies the process through marking a function as the argument of another function which is expected to use or otherwise call it at some point.

Play with the example on Repl.it!