Decorators

Decorators refer

Decorator Type

Explanation

Use Case

Pros

Cons

@function_decorator

Wraps and modifies a function’s behavior

Logging, validation, caching

1. Cleaner logic reuse 2. Keeps functions modular

1. Harder to debug deeply nested decorators

@staticmethod

Method bound to the class, not to an instance

Math utilities, class-level helper functions

1. No self required 2. Groups functionality logically

1. Can't access or modify class or instance variables

@classmethod

Method bound to the class; receives cls as the first arg

Factory methods, alternative constructors

1. Access to class-level data 2. Used for class-wide state logic

1. No access to instance (self)

@property

Getter method turned into an attribute

Accessing computed values like area, price

1. Clean attribute-like access 2. Useful for read-only fields

1. Can't accept arguments

@functools.wraps

Preserves original metadata of decorated function

Any custom decorator

1. Retains docstrings & names 2. Essential for clean introspection

1. Requires functools import

@contextlib.contextmanager

Allows creating context managers using yield

Managing resources (e.g., open files)

1. Cleaner resource handling 2. Less boilerplate

1. Needs try/finally for robustness

@dataclass

Auto-generates methods like __init__, __repr__

Data container classes

1. Saves time & code 2. Improves readability

1. Not suitable for logic-heavy classes

@lru_cache

Caches return values of a function with given arguments

Expensive or recursive functions

1. Major performance boost 2. Easy to use

1. Only works with hashable inputs

@cached_property

Caches a property’s value after first call

Expensive one-time computations

1. Memory-efficient 2. Used like a property

1. Python 3.8+ only

@singledispatch

Function overloading based on argument type

Type-specific operations

1. Cleaner alternative to if-else type checks

1. Only dispatches on the first argument

@typechecked (via library)

Validates input/output types at runtime

Type safety

1. Prevents silent type bugs 2. Useful in production

1. Extra dependency

Custom Decorator

User-defined decorator for reusable logic

Auth checks, time logging, input validation

1. Flexible & reusable 2. Encapsulates logic

1. Slightly more verbose

Chained Decorators

Applying multiple decorators to one function

Logging + caching + validation

1. Clean modular layers 2. Easy to combine behaviors

1. Order-sensitive

Class Decorator

Affects class-level behavior (entire class wrapped)

Registering models, singleton pattern

1. Dynamic class transformation 2. No metaclass needed

1. Can confuse code readers


Comparison: @staticmethod vs @classmethod vs Regular Method

Feature

@staticmethod

@classmethod

Regular Method

Access to self

Access to cls

Usage

Utility functions

Class-wide operations, factory methods

Instance-specific logic

Example Use

Math utils

From-config constructor

Changing object’s attributes


Last updated