Decorators in Python
Decorators in Python are a powerful feature that allows you to modify or extend the behavior of functions or methods without changing their actual code.
Decorators are widely used in logging, authentication, validation, performance monitoring, and automation frameworks.
Functions are First-Class Objects
In Python, functions can be:
- Assigned to variables
- Passed as arguments
- Returned from other functions
def greet():
print("Hello")
say_hello = greet
say_hello()
Function Inside Another Function
def outer():
print("Outer function")
def inner():
print("Inner function")
inner()
outer()
Function Returning Another Function
def outer():
def inner():
print("Hello from inner")
return inner
func = outer()
func()
What is a Decorator?
A decorator is a function that takes another function as an argument and returns a new function with enhanced behavior.
Simple Decorator Example
def my_decorator(func):
def wrapper():
print("Before function execution")
func()
print("After function execution")
return wrapper
def say_hi():
print("Hi!")
say_hi = my_decorator(say_hi)
say_hi()
Using @ Decorator Syntax
Python provides the @ symbol to apply decorators easily.
@my_decorator
def say_hello():
print("Hello!")
Decorator with Arguments
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Arguments:", args)
return func(*args, **kwargs)
return wrapper
@my_decorator
def add(a, b):
return a + b
print(add(5, 3))
Multiple Decorators
def decorator1(func):
def wrapper():
print("Decorator 1")
func()
return wrapper
def decorator2(func):
def wrapper():
print("Decorator 2")
func()
return wrapper
@decorator1
@decorator2
def show():
print("Hello World")
show()
Built-in Decorators in Python
- @staticmethod
- @classmethod
- @property
@staticmethod Example
class MathUtils:
@staticmethod
def add(a, b):
return a + b
Decorator with Timing Example
import time
def calculate_time(func):
def wrapper():
start = time.time()
func()
end = time.time()
print("Execution time:", end - start)
return wrapper
@calculate_time
def test_function():
for i in range(1000000):
pass
test_function()
Decorators in Automation Testing
def retry(func):
def wrapper():
for i in range(3):
try:
func()
break
except:
print("Retrying...")
return wrapper
@retry
def click_button():
print("Clicking button")
Best Practices
- Use
functools.wrapsto preserve metadata - Keep decorators simple and readable
- Avoid deeply nested decorators
Common Interview Questions
- What is a decorator?
- Why use decorators?
- Difference between function and decorator?
- What are built-in decorators?
Conclusion
Decorators in Python help extend functionality without modifying existing code. They are a powerful feature used heavily in frameworks, automation testing, and real-world applications.
👉 Learn more advanced Python concepts on way2testing.com
No comments:
Post a Comment