Skip to content

Commit bd0adc1

Browse files
authored
Update decorator-kwargs-args.md
1 parent c7f165f commit bd0adc1

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

contrib/advanced-python/decorator-kwargs-args.md

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,4 +90,57 @@ The number of elements in kwargs = 5
9090
A dictionary with keys and values is obtained.
9191

9292
## Decorators (@decorators)
93-
Now that we understand what first class object, *args, **kwargs is, we can move to decorators.
93+
Now that we understand what first class object, *args, **kwargs is, we can move to decorators. Decorators are used to perform a task that needs to be performed for existing functions. If some task has to be performed for each function, we can write a function which will perform the task without us having to make changes in each function.
94+
95+
**Sample Code:**
96+
```
97+
import time
98+
def multiplication(a,b):
99+
start=time.time()
100+
c=a*b
101+
total=time.time()-start
102+
print("Time taken for execution of multiplication",total)
103+
return c
104+
105+
def addition(a,b):
106+
start=time.time()
107+
c=a+b
108+
total=time.time()-start
109+
print("Time taken for execution of addition ",total)
110+
return c
111+
112+
multiplication(4,5)
113+
addition(4,5)
114+
```
115+
116+
In the above code, we had to calculate time and print the execution time seperately for each function leading to repeatation of code. This is where decorators come in handy.
117+
The same functionality can be achieved with the help of a decorator.
118+
119+
**Here's how:**
120+
```
121+
import time
122+
def time_find(function):
123+
def wrapper(*args, **kwargs):
124+
starttime=time.time()
125+
function(*args, **kwargs)
126+
total=time.time()-starttime
127+
print(f"Time Taken by {function.__name__} to run is ",total)
128+
return wrapper
129+
130+
@time_find #to use a decorator, simply use @<decorator name> above a function.
131+
def multiply(a, b):
132+
print(a*b)
133+
134+
@time_find
135+
def addition(a,b):
136+
print(a+b)
137+
138+
multiply(4,5)
139+
addition(4,5)
140+
```
141+
142+
The above method eleminates redundant code and makes the code cleaner. You may have observed that we have used *args and **kwargs in the wrapper function. This is so that this decorator function is flexible for all types of functions and their parameters and this way it can find out the execution time of any function with as many parameters as needed, we just need to use our decorator @time_find.
143+
144+
145+
146+

0 commit comments

Comments
 (0)