Python Decorators and Closures
In Python, decorators and closures are advanced features that enable flexible, reusable, and elegant programming patterns. They are widely used in functional programming, logging, authentication, and code optimization. Understanding them helps you write cleaner and more modular code.
🌍 Closures in Python
A closure is a function that retains access to variables from its enclosing scope, even after that scope has finished executing.
Example: Closure Retaining State
def make_multiplier(x):
def multiplier(n):
return x * n
return multiplier
double = make_multiplier(2)
print(double(5)) # Output: 10
Here, multiplier remembers the value of x even after make_multiplier has returned.
Use cases of closures:
- State retention
- Encapsulation
- Callbacks
- Memoization
🛠️ Decorators in Python
A decorator is a function that takes another function as input and extends or modifies its behavior without changing its source code. Decorators are built on closures.
Example: Function Decorator
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Output:
Before function call
Hello!
After function call
✨ Built-in Decorators
- @staticmethod: Defines a method that doesn’t depend on object state.
- @classmethod: Defines a method that receives the class as the first argument.
- @property: Creates managed attributes with getters/setters.
🔎 Decorators vs. Closures
| Feature | Closures | Decorators |
|---|---|---|
| Definition | Inner functions that capture enclosing scope variables | Functions that modify other functions |
| Purpose | Retain state, encapsulate logic | Extend/modify behavior of functions |
| Syntax | Defined inside another function | Applied with @decorator_name |
| Example Use | Memoization, callbacks | Logging, authentication, validation |
📖 Conclusion
Closures allow functions to retain state and encapsulate logic, while decorators provide a clean way to extend functionality without altering source code. Together, they form the backbone of Python’s expressive and modular programming style.
No comments:
Post a Comment