Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
community creator

How to use decorators in Python

Divyanjali Vallapu Reddy

Decorators are used to extend a functions functionality without changing its existing code.

Before we go deeper into decorators, lets understand functions.

If you are already comfortable with functions, skip ahead.

Functions are part of the modular programming technique that helps divide a problem into many sub-problems. Each function has a task to perform and its code block is identified by a given name.

Python function declaration

The def statement is the most common way to define a function in Python.

def function-Name(Parameters List):
     '''block'''

Below is an example of how to declare a function:

def Unitprice(Amount,Quantity):
	return Amount / Quantity

The function above returns unit price by dividing the amount by the quantity.

Python function call

There are two main ways to call the function.

Direct method

Calls the function with its name and brackets. The function is invoked using its name and is followed by parameters contained within brackets. Example : Unitprice( 500,25)

def Unitprice(Amount,Quantity):
	return Amount / Quantity
print(Unitprice(500,25))

Indirect method

This method uses the closure property.

It is a two-step process:

  1. The function is invoked using its name without any brackets. Example: Y = Unit price (as shown in the code below).

Note: Python functions are objects. In the below statement, the function is assigned to object ‘Y’.

def Unitprice(Amount,Quantity):
	return Amount / Quantity
Y=Unitprice 
print(Y(500,25))
  1. Call the function using object Name, i.e., Y(500,25)

This second method is used by decorators.

Nested functions and closure in Python

A function that is part of another function is called a “Nested" or “Inner" function.

Examine the two code segments below

“Branch” is a function that is embedded in another function, “Tree”.

In program one, we are executing the “Branch” function inside “Tree":

def Tree():
    Num_of_leaves_in_branch = 5
    def Branch():
        return  Num_of_leaves_in_branch
    return Branch #Note: getting ‘Branch’ function reference inside ‘Tree’ function. No curve braces
# Main Program
X= Tree()
print(X()) # call function using variable X
program one

In program two, we are just getting the function reference and calling it in the main program. This techniquewhen a code segment is assigned to a variable. is called “Closure” in Python:

def Tree():
  Num_of_leaves_in_branch = 5
  def Branch():
    return  Num_of_leaves_in_branch
  return Branch
x=Tree()
print(x())
program two

Decorators

Decorators are used to decorate a given function using the closure property.

Decorators are very useful when we are not allowed to change the existing function’s code but still need to change its behavior.

Take a look at the example:

# can’t handle zero division
def Unitprice (Amount,Quantity):
  return Amount / Quantity
# Main Program
print (Unitprice(500,0))
Note: The above code segment gives an error at run time because division with a denominator of zero is infinite.

Now, let’s solve that zero division error using decorators. Follow these directions and then look at the code below:

  1. Use the @ symbol followed by the decorator_function_name.
  1. Decorator function “Div_by_zero” is written to decorate the “Unitprice” function module.

The purpose of this Wrapper function is to handle zero division.

  1. Control is automatically transferred to the wrapper function when “Unitprice” is called.
  2. The decorator function “Div_by_zero” receives the function name as a parameter.
# can handle zero division using decorator
def Div_by_zero(func):
  def inner(x,y):
    if y ==0:
      return "Quantity is zero"
    return func(x,y)
  return inner      
@Div_by_zero
def Unitprice (Amount,Quantity):
  return Amount / Quantity

# Main Program
print (Unitprice(500,0))
Note: The above code segment does handle zero division due to decorator

RELATED TAGS

python
community creator

CONTRIBUTOR

Divyanjali Vallapu Reddy
RELATED COURSES

View all Courses

Keep Exploring