Wednesday, February 25, 2026

Python Decorators and Closures

 

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

FeatureClosuresDecorators
DefinitionInner functions that capture enclosing scope variablesFunctions that modify other functions
PurposeRetain state, encapsulate logicExtend/modify behavior of functions
SyntaxDefined inside another functionApplied with @decorator_name
Example UseMemoization, callbacksLogging, 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

Support Vector Machines in Machine Learning

Support Vector Machines in Machine Learning Introduction Support Vector Machines (SVMs) are powerful supervised learning algorithms used ...