DECORATORS

Adding functionality without changing the main function is called Decorators.

A decorators is a function which takes another function as an argument, add some extra functionality and return another function without altering The source code of the original function.

Decorators also called as META Programming

reason:A part of the program Tries to modify another part of the program at compile time.

GENERAL STRUCTURE OF DECORATOR

1)A decorators function must be an nested function were in the outer function must take only one argument (Decorator function address)

2)The nested/inner function must take variable numbers of arguments.

3)The outer function must return the nested/inner function address.

4)The parameters of the outer function should be called inside the nested function.

syntax:

def outer (func):

def inner(*args, **kwargs):

print(modified main func)

func(*args, **kwargs)

return inner

@outer

def main_func():

statements

return statement

print(main_func(arguments)\

Example:

WADF TO ADD 2 NUMBERS AND DISPLAY THE MESSAGE BEFORE AND AFTER PERFORMING THE ADDITION

def addition(func): #func==add

def inner(*args):

print("im performing addition")

func(*args)

print("addition is done")

return inner

@addition

def add(*args):

c=sum(args)

print(c)

add(1,2,3,4,5,3,4,6,8)

Common Use Cases of Decorators:

  1. Logging: Record function calls, arguments, and return values.
  2. Timing: Measure the execution time of functions.
  3. Caching: Store function results for faster subsequent calls.
  4. Authentication: Check user credentials before allowing function execution.
  5. Error Handling: Provide custom error handling for functions.
Contributer : Rohit Singh Rawat

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *