How to Use Decorators in Python, by example (2024)

How to Use Decorators in Python, by example (3)

A decorator in Python is a function that takes another function as its argument, and returns yet another function. Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.

Consider the following example:

1. add_together function

The simple add_together function takes 2 integers as arguments and returns the summation of the 2 integer values passed.

How to Use Decorators in Python, by example (4)

1.1. Extending the functionality of add_together with a decorator

Lets propose the following scenario. We would like add_together to be able to take a list of 2 element tuples as its argument and return a list of integers which represents the summation of their values. We can achieve this through the use of a decorator.

Firstly, we give the decorator a sensible name which intimates what its intended purpose is. Here the decorator, called decorator_list is simply a function that takes another function as its argument. This function has been named ‘fnc’ in the arguments list to decorator_list.

Inside the decoratored function, we define a local function called inner. The inner function takes a list of 2-element tuples as its argument. The inner function loops through this list of 2 element tuples, and for each tuple applies the original function, add_together, with index position 0 of the tuple being the argument to a in add_together and index position 1 being the argument to b in add_together. The inner function returns a list of these values summed up. The decorator_list function finally returns the inner function.

Now, let's apply this logic and see how the decorator function works.

To apply the decorator, we use the syntax @, followed by the function name of the decorator above the function that is being decorated. This is syntactically the same as:

How to Use Decorators in Python, by example (2024)
Top Articles
Latest Posts
Article information

Author: Nathanial Hackett

Last Updated:

Views: 5403

Rating: 4.1 / 5 (72 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Nathanial Hackett

Birthday: 1997-10-09

Address: Apt. 935 264 Abshire Canyon, South Nerissachester, NM 01800

Phone: +9752624861224

Job: Forward Technology Assistant

Hobby: Listening to music, Shopping, Vacation, Baton twirling, Flower arranging, Blacksmithing, Do it yourself

Introduction: My name is Nathanial Hackett, I am a lovely, curious, smiling, lively, thoughtful, courageous, lively person who loves writing and wants to share my knowledge and understanding with you.