Decorators and Generators in Python
#Decorars Generators in Python
Python is known for its simplicity and flexibility. Two powerful features that make Python stand out are Decorators and Generators. These concepts help developers write cleaner, more efficient, and reusable code. In this article, weβll explore what they are, how they work, and provide examples to help you master them.
A decorator in Python is a special function that modifies the behavior of another function or class without changing its code. Decorators are widely used in logging, authentication, caching, and framework development (e.g., Django, Flask).
def my_decorator(func):
def wrapper():
print("Before the function runs")
func()
print("After the function runs")
return wrapper
@my_decorator
def say_hello():
print("Hello, World!")
say_hello()
Output:
Before the function runs
Hello, World!
After the function runs
π Here, the @my_decorator
syntax applies the decorator to say_hello()
.
Logging function calls
Checking user authentication
Measuring execution time
Enforcing access control
Code reusability and cleaner syntax
A generator in Python is a function that returns an iterator using the yield
keyword. Unlike normal functions that return a single value, generators yield multiple values one at a time and maintain their state between calls.
This makes them memory-efficient and ideal for handling large datasets or infinite sequences.
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for number in count_up_to(5):
print(number)
Output:
1
2
3
4
5
π Here, yield
allows the function to return values one at a time without storing the entire sequence in memory.
Memory Efficiency β Generate data on the fly instead of storing it.
Infinite Sequences β Useful for streams and pipelines.
Improved Performance β Faster for large-scale data processing.
Feature | Decorators | Generators |
---|---|---|
Purpose | Modify behavior of functions or classes | Produce values one at a time |
Keyword Used | @decorator syntax | yield keyword |
Use Case | Logging, caching, authentication | Iteration, handling large datasets |
Return Type | Function | Iterator |
Both decorators and generators are advanced features that make Python programming more powerful.
Use decorators when you need to extend or modify function behavior without rewriting code.
Use generators when working with large data streams to save memory and improve performance.
By mastering these, you can write more efficient, reusable, and Pythonic code.