Function Decorators in Python | Kit 1 (Introduction)

Python Methods and Functions

Background

The following are important facts about functions in Python that are useful for understanding decorator functions.

  1. In Python we can define a function inside another function.
  2. In Python, a function can be passed as a parameter to another function (a function can also return another function).

# Python program to demonstrate that a function
# can be defined inside another function and
Function # can be passed as a parameter.

 
# Adds a welcome message to the line

def messageWithWelcome ( str ):

  

# Nested function

def addWelcome ():

return "Welcome to"

 

# Return the concatenation addWelcome ()

No. and street

return   addWelcome () + str

 
# Get site name to which the greeting is appended

def site (site_name):

return site_name

 

print messageWithWelcome (site ( "GeeksforGeeks" ))

Output:

 Welcome to Python.Engineering 

Function Decorator

Decorator — it is a function that takes a function as its only parameter and returns a function. It's useful to wrap functionality with the same code over and over again. For example, the above code could be rewritten as follows.

We use @func_name to specify a decorator that will be applied to another function.

# Adds a welcome message to the line
# fun () is returned. Have fun () like
# parameter and return welcome ().

def decorate_message (fun):

 

# Nested function

def addWelcome (site_name):

  return " Welcome to " + fun (site_name)

 

# Decorator returns function

return addWelcome

 
@ decorate_message

def site (site_name):

return site_name; 

 
# Driver code

 
# This call is equivalent to a call
# decorate_message () with function
# site (& quot; Python.Engineering & quot;) as parameter

print site ( "GeeksforGeeks" )

Output:

 Welcome to Python.Engineering 

Decorators also can be useful for attaching data (or adding an attribute) to functions.

# Python example to demonstrate that
# decorators might be useful to attach data

 
# Decorator function for attaching
# data for functions

def attach_data (func):

func.data = 3

return func

 
@ attach_data

def add (x, y):

  return x + y

 
# Driver code

  
# This call is equivalent to attach_data ()
# with add () as a parameter

print (add ( 2 , 3 ))

 

print (add.data)

Output:

 5 3 

add () returns the sum of the x and y arguments passed as arguments, but it is wrapped in the decorator function, calling add (2, 3) will just give the sum of the two numbers, but when we call add.data, then the add function is then passed to the decorator function & # 39; attach_data & # 39; as an argument, and this function returns the function & # 39; add & # 39; with the attribute & # 39; data & # 39; set to 3 and therefore prints it.

Python decorators — it is a powerful tool for removing redundancy.

Please refer to the

Tutorials