What Are Decorators In Python?
Published on October 03 2023
In this tutorial, we will learn what decorators are in Python and understand them in detail with an example. This tutorial is part of Python's top 25 most commonly asked interview questions.
Definition
- Decorators are functions that add functionality to an existing function in Python without changing the structure of the function itself.
- It receives a function as input and returns a function as output.
- represented by @decorator_name
Steps
- To apply a decorator we first define the decorator function.
- Then we write the function it is applied to
- and simply add the decorator function above the function it has to be applied to.
Sample Decorator
@validate_divide_inputs_function
def perform_divide(x, y):
Applications
- These are useful when we want to dynamically increase the functionality of an existing function without changing it.
- validating input data, enforcing access control and authentication, caching, etc.
Example
def validate_divide_inputs_function(func):
def inner_validation_function(x, y):
if y == 0:
print('Cannot divide by 0')
return
else: # else can be avoided
result_op = func(x,y)
return result_op
return inner_validation_function
@validate_divide_inputs_function
def perform_divide(x, y):
result = x / y
return result
output_result = perform_divide(102,0)
print(output_result)
To know about it, please refer to the official documentation website - official website.
Example Video
Next Tutorial
- What Is Python, Its Benefits And Features?
- What Is Pickling And Unpickling In Python?
- Memory Management In Python
- What Is The __Init__ In Python?
- Difference Between List And Tuple
- What Is The Self Keyword In Python?
- What Is The Lambda Function In Python?
- What Is A Break, Continue, And Pass Statement In Python?
- What Are The Common Built-In Data Types In Python?
- What Is The Difference Between .Py And .Pyc Files In Python?
- What Are Decorators In Python?
- What Is Slicing In Python?
- What Are Negative Indexes In Python?
- What Is List And Dictionary Comprehension In Python?
- What Is A Docstring In Python?
- What Are Python Iterators?
- What Are *Args And **Kwargs In Python And How To Use Them?
- What Is The Pythonpath Variable In Python?
- What Are Namespaces In Python?
- What Is Pep8 (Python Enhancement Proposals) In Python?
- What Is The Split(), Join(), Sub(), And Subn() Method In Python?
- What Are Modules And Packages In Python?
- What Is Scope Resolution In Python?
- Is Python Compiled Or Interpreted Language?
- What Are Generators In Python?