#100DaysOfCode in Python Transcripts
Chapter: Days 22-24: Decorators
Lecture: Write a timeit decorator (wraps)
0:00 Let's do a more realistic
0:02 and interesting example, let's write a timeit decorator.
0:14 And as we said before, we call the decorated function,
0:17 and we add some behavior before and after calling it.
0:29 Alright, we got that defined, so we
0:32 have a decorator called timeit.
0:34 It receives a function, it wraps the function,
0:37 and we will see in a bit why that is.
0:39 We pass it the args and the keyword args.
0:42 We start a timer, we call the function,
0:45 we end the timer, and then we print
0:47 how much time that function took.
0:49 We return the wrapper, and that's it.
0:52 Let's then define a function that
0:53 we can use this decorator on.
1:02 So that in itself is not decorated yet,
1:05 so let's define it again using the decorator.
1:12 And look at that, how cool is that?
1:14 So the decorator started the timer,
1:16 it ran the function, it measured the time,
1:20 and after the function was complete,
1:22 it reported back how long it took.
1:24 So it took two seconds which of course is not a surprise.
1:27 A final note about wraps, so what if
1:29 I wouldn't have done wraps function?
1:33 So let's take that temporarily out.
1:40 And let's inspect that function.
1:45 Hey, where is my doc string?
1:50 It disappeared. Not good, let's put it back.
1:55 Let's define the function again using the decorator.
2:00 And there you go, so that's why you should always use wraps
2:04 from the functools module, to preserve your doc strings.