decorators

In essence, a decorator is a function that takes another function as an argument and returns a modified version of that function. They use the @ symbol followed by the decorator’s name above the function definition they are applied to.

Think of them as wrappers around functions. The wrapper adds functionality before or after the original function executes, or even modifies its arguments or return value. This promotes code reusability and avoids repetitive boilerplate code.

Real-world contexts: Decorators are commonly used for:

  • Logging: Automatically logging function calls and their parameters.
  • Authentication/Authorization: Checking if a user is authenticated before allowing them to access a resource.
  • Timing: Measuring the execution time of functions.
  • Caching: Storing the results of expensive function calls to avoid recomputation.
  • Input Validation: Ensuring that function arguments meet certain criteria.