#100DaysOfCode in Python Transcripts
Chapter: Days 22-24: Decorators
Lecture: Write a timeit decorator (wraps)

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Let's do a more realistic and interesting example, let's write a timeit decorator. And as we said before, we call the decorated function,
0:18 and we add some behavior before and after calling it. Alright, we got that defined, so we have a decorator called timeit.
0:35 It receives a function, it wraps the function, and we will see in a bit why that is. We pass it the args and the keyword args.
0:43 We start a timer, we call the function, we end the timer, and then we print how much time that function took. We return the wrapper, and that's it.
0:53 Let's then define a function that we can use this decorator on. So that in itself is not decorated yet, so let's define it again using the decorator.
1:13 And look at that, how cool is that? So the decorator started the timer, it ran the function, it measured the time, and after the function was complete,
1:23 it reported back how long it took. So it took two seconds which of course is not a surprise. A final note about wraps, so what if
1:30 I wouldn't have done wraps function? So let's take that temporarily out. And let's inspect that function. Hey, where is my doc string?
1:51 It disappeared. Not good, let's put it back. Let's define the function again using the decorator.
2:01 And there you go, so that's why you should always use wraps from the functools module, to preserve your doc strings.


Talk Python's Mastodon Michael Kennedy's Mastodon