Python Decorators: A Practical Guide
- arpitnearlearn
- May 5, 2023
- 2 min read

Python Decorators: A Practical Guide
Python decorators are a powerful feature that allows programmers to modify the behaviour of a function or class without having to change its source code. This article aims to provide a practical guide to understanding and using decorators in your Python code.
What are Decorators?
Decorators are functions that take another function as input and return a modified version of that function. In other words, decorators are a way to wrap a function and modify its behavior without changing its source code.
The syntax for using decorators is as follows:
ruby
Copy code
@decorator_function
def my_function():
# function body
Here, decorator_function is the name of the function that will modify my_function. The @ symbol is used to indicate that decorator_function is a decorator for my_function.
Decorators can be chained together, which means that multiple decorators can be applied to a single function:
less
Copy code
@decorator_function1
@decorator_function2
def my_function():
# function body
In this case, decorator_function2 will modify the function returned by decorator_function1.
Creating Decorators
Creating a decorator in Python is relatively simple. A decorator is just a regular Python function that takes another function as an argument and returns a modified version of that function.
Here's an example of a decorator that adds logging to a function:
python
Copy code
def logger(func):
def wrapper(*args, **kwargs):
print(f"Entering {func.__name__}")
result = func(*args, **kwargs)
print(f"Exiting {func.__name__}")
return result
return wrapper
In this example, the logger function takes another function func as an argument and returns a new function wrapper. wrapper logs the entry and exit of func and returns the result of calling func. If you're looking for training in react native, then you can check out our react native course in Bangalore.
Using Decorators
Decorators can be used to modify the behavior of a function in a variety of ways. Here are some examples of how decorators can be used:
Timing function execution:
python
Copy code
import time
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Elapsed time: {end_time - start_time:.2f} seconds")
return result
return wrapper
@timer
def my_function():
# function body
Caching function results:
python
Copy code
def memoize(func):
cache = {}
def wrapper(*args):
if args in cache:
return cache[args]
else:
result = func(*args)
cache[args] = result
return result
return wrapper
@memoize
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
Adding security checks:
python
Copy code
import functools
import getpass
def requires_password(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
password = getpass.getpass("Enter password:")
if password == "password123":
return func(*args, **kwargs)
else:
raise Exception("Incorrect password")
return wrapper
@requires_password
def my_function():
# function body
Conclusion
Python decorators are a powerful feature that can be used to modify the behaviour of functions and classes without having to change their source code. Decorators are easy to create and use, and they can be applied in a variety of situations to add functionality to your Python code. If you're looking for training in python, then you can check out our Python course in Bangalore.
Kommentare