Advanced Python Tips by Rahul Agarwal

Advanced Python Tips by Rahul Agarwal

Author:Rahul Agarwal [Rahul Agarwal]
Language: eng
Format: epub
Publisher: Independent
Published: 2020-09-12T00:00:00+00:00


What are Decorators?

In simple terms: Decorators are functions that wrap another function thus modifying its behavior.

A simple example:

Let us say we want to add custom functionality to some of our functions. The functionality is that whenever the function gets called the “function name begins” is printed and whenever the function ends the “function name ends” and time taken by the function is printed.

Let us assume our function is:

def somefunc(a,b): output = a+b return output

We can add some print lines to all our functions to achieve this.

import time def somefunc(a,b): print("somefunc begins") start_time = time.time() output = a+b print("somefunc ends in ",time.time()-start_time, "secs") return output out = somefunc(4,5) OUTPUT: ------------------------------------------- somefunc begins somefunc ends in 9.5367431640625e-07 secs

But, Can we do better?



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.