banner



What Is A Python Decorator

Decorators are a very powerful and useful tool in Python since it allows programmers to change the behaviour of function or class. Decorators allow united states to wrap another function in order to extend the behaviour of the wrapped office, without permanently modifying it. But before diving deep into decorators let us empathise some concepts that will come in handy in learning the decorators.

Starting time Class Objects
In Python, functions are beginning class objects that hateful that functions in Python can be used or passed as arguments.
Properties of starting time class functions:

  • A function is an instance of the Object type.
  • Y'all can store the role in a variable.
  • You can pass the function as a parameter to some other part.
  • You can return the function from a function.
  • You can store them in data structures such as hash tables, lists, …

Consider the below examples for better agreement.

Example one: Treating the functions equally objects.

Python3

def shout(text):

render text.upper()

print (shout( 'Hello' ))

yell = shout

print (yell( 'Hullo' ))

Output:

HELLO Hello

In the above example, we have assigned the office shout to a variable. This will not telephone call the part instead it takes the function object referenced by a shout and creates a second name pointing to it, yell.

Instance 2: Passing the function equally an statement

Python3

def shout(text):

render text.upper()

def whisper(text):

return text.lower()

def greet(func):

greeting = func( )

print (greeting)

greet(shout)

greet(whisper)

Output:

HI, I AM CREATED By A Role PASSED As AN Argument. hi, i am created past a office passed as an argument.

In the in a higher place example, the greet function takes another function every bit a parameter (shout and whisper in this case). The function passed as an statement is so called inside the part greet.

Example iii: Returning functions from another office.

Python3

def create_adder(x):

def adder(y):

return x + y

return adder

add_15 = create_adder( 15 )

print (add_15( 10 ))

Output:

25

In the above case, we have created a part inside of another function and and then have returned the office created inside.
The above iii examples depict the important concepts that are needed to understand decorators. After going through them let us now dive deep into decorators.

Decorators

As stated above the decorators are used to modify the behaviour of function or class. In Decorators, functions are taken every bit the argument into another function and then chosen within the wrapper office.

Syntax for Decorator:

@gfg_decorator def hello_decorator():     impress("Gfg")  '''Above code is equivalent to -  def hello_decorator():     print("Gfg")      hello_decorator = gfg_decorator(hello_decorator)'''

In the above lawmaking, gfg_decorator is a callable part, will add some code on the top of some some other callable part, hello_decorator function and return the wrapper function.

Decorator can modify the behaviour:

Python3

def hello_decorator(func):

def inner1():

impress ( "Hullo, this is earlier function execution" )

func()

print ( "This is subsequently function execution" )

return inner1

def function_to_be_used():

print ( "This is inside the function !!" )

function_to_be_used = hello_decorator(function_to_be_used)

function_to_be_used()

Output:

Hello, this is before function execution This is inside the office !! This is after function execution

Let's see the behaviour of the above lawmaking how information technology runs step past step when the "function_to_be_used" is chosen.


Let's bound to another example where we can easily detect out the execution time of a office using a decorator.

Python3

import time

import math

def calculate_time(func):

def inner1( * args, * * kwargs):

brainstorm = time.time()

func( * args, * * kwargs)

end = fourth dimension.fourth dimension()

print ( "Total fourth dimension taken in : " , func.__name__, end - begin)

render inner1

@calculate_time

def factorial(num):

time.slumber( two )

print (math.factorial(num))

factorial( 10 )

Output:

3628800 Total fourth dimension taken in :  factorial ii.0061802864074707

What if a office returns something or an statement is passed to the function?

In all the above examples the functions didn't return anything then there wasn't whatever issue, merely one may need the returned value.

Python3

def hello_decorator(func):

def inner1( * args, * * kwargs):

print ( "before Execution" )

returned_value = func( * args, * * kwargs)

print ( "after Execution" )

render returned_value

return inner1

@hello_decorator

def sum_two_numbers(a, b):

impress ( "Inside the function" )

return a + b

a, b = one , 2

print ( "Sum =" , sum_two_numbers(a, b))

Output:

before Execution Inside the function after Execution Sum = 3

In the above example, yous may notice a keen deviation in the parameters of the inner function. The inner function takes the argument equally *args and **kwargs which means that a tuple of positional arguments or a dictionary of keyword arguments can be passed of any length. This makes information technology a full general decorator that can decorate a office having any number of arguments.

Chaining Decorators

In simpler terms chaining decorators means decorating a function with multiple decorators.

Example:

Python3

def decor1(func):

def inner():

ten = func()

return ten * 10

return inner

def decor(func):

def inner():

10 = func()

return 2 * x

render inner

@decor1

@decor

def num():

return 10

impress (num())

Output:

400

The above case is like to calling the role as –

decor1(decor(num))

What Is A Python Decorator,

Source: https://www.geeksforgeeks.org/decorators-in-python/

Posted by: bradshawcoord1984.blogspot.com

0 Response to "What Is A Python Decorator"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel