What is a Python decorator?
Python decorators allow us to change the behaviour of a function without permanently making changes to the syntax of that function. This simply means that we can use a decorator which is usually another function to modify the behaviour of a class or function.
This is largely possible because in Python functions are first-class citizens. Therefore this means that we can pass a function as a parameter to another function or return a function from another function.
In this article, we are going to use a really basic example to explore how we can create a decorator and how we can use it. This example also illustrates the concept of metaprogramming where a part of the program tries to modify another program at compile time.
Declaring our example code
So we will start off by creating a simple function that simply prints out a message when executed. We have named the function learn_to_code().
Modify the function
Now that we have our target function in place we wish to create a decorator that will try to modify the above function. We are going to create a function that will allow us to split the string returned by the learn_to_code() function into a list.
In order to achieve this, we are going to make use of the concept of higher-order functions and nesting. This means that we will create a function that takes another function as an argument.
We are going to name this function split_string(), which this the main function that accepts another function as an argument. Now within this function, we have also nested another function named the wrapper() function.
Using the wrapper function
Now within the wrapper function, we have assigned the output from the function passed as an argument to the split_string() function to a variable named func. Finally, we have made use of the built-in split() function to split the string that will be returned by the learn_to_code() function into a list.
def split_string(function):
def wrapper():
func = function()
str_list = func.split()
return str_list
return wrapper
The split function normally accepts two optional parameters, a separator and a max split that specifies the number of splits to be performed.
string.split(separator, maxsplit)
However, when the two parameters are not specified the interpreter will by default use the whitespace as the separator and a default value of ‘-1’ as the maxsplit.
Applying a Python decorator
Now to apply this decorator function to the function we created earlier we will make use of the @ symbol followed by the name of the decorator function as shown below. Now when we run the code below we will get the string returned by the learn_to_code() function split into a list.
Applying a Python Decorator to Multiple Functions
We can also apply a single decorator to multiple functions improving code reusability in the process. To demonstrate this concept we will create another function that returns the names of animals.
Using Python decorators with the @ symbol
In a similar manner, we can also apply the Python decorators function that we created earlier on to this function using the @ symbol and the name of the decorator function.
Summary
If you’d like to see more programming tutorials, check out our Youtube channel, where we have plenty of Python video tutorials in English.
In our Python Programming Tutorials series, you’ll find useful materials which will help you improve your programming skills and speed up the learning process.
Programming tutorials
- How to use the Python for loop
- How to use Python Sets
- How to use a Python Dictionary
- How to use Python Classes
- How to use Python Range
- How to use Python if-else statements
- How to use Python RegEx
- How to use Python Lists
- How to use Python Enumerate
- How to use Python Functions
- How to use Python Split
- How to use Python Try-Except
- How to use Python Tuples
- How to use Python Arrays
- How to use Python Sort
- How to use the Python DateTime
- How to download Python?
- How to use the Python FileWrite function
- How to use Python Lambda
- How to use Python ListAppend
- How to use Python ListComprehension
- How to use Python Map
- How to use Python Operators
- How to use Python Pandas
- How to use Python Requests
- How to use Python Strings
- How to use Python Count
- How to use Python Comments
- How to use the Python File Reader method
- How to use the Python IDE-s
- How to use Python logging
- How to use Python Print
- How to use the Python Zip
- How to use Python Append
- How to use Python Global Variables
- How to use the Python join method
- How to use Python list length
- How to use Python JSON files
- How to use Python Modulo
- How to use Python file opening methods
- How to use Python round
- How to use Python sleep
- How to use Python replace
- How to use Python strip
- How to use the Python Time module
- How to use Python unittests
- How to save data to a text file using Context Manager?
- How to use Python external modules
- How to use Python find
- How to install the Python pip package manager
- How to delete files in Python
- Parsing XML files in Python
- How to make a GUI in Python
- How to use Python in Command Prompt
- How to Run a Python Program in VS Code
- How to run a program in Python IDLE
- How to run a program in Jupyter Notebook
- How to read a text file in Python
- How to add numbers in Python
- How to ask for user input in Python
- How to debug in Python
- How to create a thread in Python
- How to end a program in Python
- How to import a library in Python
- How to use the PIP package manager
- How to use classes in Python
- How to reverse strings in Python
- How to convert a string to int in Python
- How to print on the same line in Python
- How to remove items from a list
- How to add to a dictionary in Python
- How to raise an exception in Python
- How to throw an exception in Python
- How to stop a program in Python
- How to use Python assert
- How to use the Python compiler
- How to use Python decorator
Would you like to learn how to code, online? Come and try our first 25 lessons for free at the CodeBerry Programming School.
Learn to code and change your career!

100% ONLINE

IDEAL FOR BEGINNERS

SUPPORTIVE COMMUNITY

SELF-PACED LEARNING
Not sure if programming is for you? With CodeBerry you’ll like it.
