Python Decorators Tutorial
Key Takeaways
Explains decorators in Python using a simple example of measuring execution time
Full Transcript
dear friends we are going to look at decorators in Python today now when you read about decorators online it sounds like a complex concept but it's really not that complex and the goal of this tutorial is to explain decorators in a very simple easy way ok so the way we are going to start this tutorial is first let's discuss what problem decorators will try to solve right like what is really the need of decorators here I have two functions calculate square and calculate cube and what these functions are doing is for example let's look at this function first this function is taking an array of numbers as an input it's just I trading through the array and calculating the square of that number and putting that into a result calculate cube does the same thing but instead of square it is calculating a cube ok very very easy functions and here I am calling those functions for a range of 1 to this number now often you have a need of measuring the performance of a function and by performance I mean how much time does every function take to execute and in order to measure the timing you have to use the time module I mean this is one of the ways I usually like to do that where I will take the start time so what this will do is when function execution at is at this point it will take the start time and once you are done you will take the end time and here you will say calculate square toke how much did it take so it takes an - start in 2000 so this will give you a result in seconds and I am multiplying it by thousand just to produce a result in millisecond so this will say okay it took this many millisecond alright and we do the same thing for this function because you want to measure the performance of both of these functions okay okay and I'm calling these functions here down below okay pretty straightforward when I run the program I see the performance that the first function took 14 milliseconds the second one took 19 now the problem with this code is that let's say you have a complex software project when you have but returned 200 functions so in in order to measure the performance of all those 200 functions you have to write the start time end time the exactly same line of code in every function now this is not good you see like these lines are getting repeated start and both of these lines are getting repeated in every function that you want to measure the performance second problem is that there is a logic in this function now that logic is combined with the timing logic okay so the main logic of this function is to calculate square now you are cluttering that logic with the timing code and it makes code less readable there has to be a better way of doing this and that better way is basically decorator so decorator allows you to wrap your function in another function so let me show you how you do that so first I am going to remove this timing code all right so this is purely a timing code which I am removing and I want to have a function which has just the logic that that function is supposed to do so this function looks now much clean so in order to do decorator first you need to define the wrapper function so I'm going to call my wrapper function time it and that wrapper function will take function as an argument now functions are first class objects in Python what I mean by that is you can pass function as an argument to a function you can return function as a return value from another function okay you will understand this as we continue writing our code so in this function I'm going to define another function okay and call it a wrapper so notice that Python allows you to write nested function so you can have one function inside another function and what this function is doing is it is taking the positional arguments which is your star ARBs and your keyword arguments and then it will start the timer here and then it will call the function that was passed as an argument so I'm going to call function here with argument and keyword argument and then I will measure the end time and in the end you will say function dot underscore new score name so this underscore underscore name will return you the name of that function okay and this function took how much it took and - start so this piece of code is same as what we wrote before you want to measure the time of function in millisecond that's why you are doing this okay and of course you want to return the result all right and what so he this is my inner function okay and here my function ends and at this point I want to return this wrapper function here so again I'm returning a function from another function that's why this function is called a first-class object you can treat it just like your normal variable you can return it you can pass it as a function argument and so on okay so let's let's first run the program and I will give you more details on on this time it function okay so let's run it okay so it looks like there is a problem oh yeah I forgot to decorate it so I created this timing function now what you need to do is decorate these other functions okay so the syntax is you have to say add so before this function line just say at and just say time it okay [Music] cool so you can see that now it is saying calculate Square to this many millisecond and calculate you took this many millisecond so you see the beauty now that any function that you want to measure performance off now once you have defined this code you can just put this tag at the beginning and it's gonna measure the performance so this is really good it makes this code much more readable and then all your timing core is restricted into one function okay now I'm going to show you how all of this actually walked by debugging it I have put a breakpoint here in this function in my pym I will start my debugging session okay so not in order to go inside I will place f11 so when you do this you notice that when it called calculate square function it it didn't it didn't go to here at the first line of this function because it realized that this function is decorated it needs to call time it first because time it is a wrapper so it went here and from here you can just do f10 to go to the next line now here this funk is actually calculate square so when you go inside that you notice that now the flow is coming here okay so it will go here then eventually it will come to result okay you can see that it calculated the result it's here and then when you press next you see it came back here f10 span so again it is here and f10 okay so you now kind of get an idea on how it all worked cool so again just to recapture the main highlights decorator acts as a wrapper to your original function and it and you can do things like timing your function or even logging certain lines at the beginning and end of the function so these are like some of the commonly used cases of using decorators so I hope you guys had a fun time learning decorators and I hope that I have made it little simple if you have any question please don't hesitate to put it in the comments box below thank you for watching
Original Description
Video without background music: https://youtu.be/IVWZxr0kOyI
In this tutorial, I will explain decorators in a very simple way by going over how to measure the execution time of function using decorators. They serve as a wrapper to original function but does a wonderful job of avoiding code duplication and not cluttering original code with additional logic. The video discusses why there is a need of decorators, what is a decorator, how to create decorators and what is call repper function.
Topics that are covered in this Python Video:
0:00 Explain why decorators needed?
3:52 What is a decorator?
4:18 create decorators
4:26 Call repper function
Code in this tutorial is available here: https://github.com/codebasics/py/blob/master/Advanced/decorators.py
Do you want to learn technology from me? Check https://codebasics.io/ for my affordable video courses.
Next Video:
Python unit testing - pytest parameters: https://www.youtube.com/watch?v=rN0TREj8G7U&list=PLeo1K3hjS3uv5U-Lmlnucd7gqF-3ehIh0&index=39
Website: https://codebasics.io/
Facebook: https://www.facebook.com/codebasicshub
Twitter: https://twitter.com/codebasicshub
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from codebasics · codebasics · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Python Tutorial - 1. Install python on windows
codebasics
Python Tutorial - 2. Variables
codebasics
Python Tutorial - 3. Numbers
codebasics
Python Tutorial - 4. Strings
codebasics
Python Tutorial - 5. Lists
codebasics
Python Tutorial - 6. Install PyCharm on Windows
codebasics
PyCharm Tutorial - 7. Debug python code using PyCharm
codebasics
Python Tutorial - 8. If Statement
codebasics
Python Tutorial - 9. For loop
codebasics
Python Tutorial - 10. Functions
codebasics
Python Tutorial - 11. Dictionaries and Tuples
codebasics
Python Tutorial - 12. Modules
codebasics
Python Tutorial - 13. Reading/Writing Files
codebasics
How to install Julia on Windows
codebasics
Python Tutorial - 14. Working With JSON
codebasics
Julia Tutorial - 1. Variables
codebasics
Julia Tutorial - 2. Numbers
codebasics
Python Tutorial - 15. if __name__ == "__main__"
codebasics
Julia Tutorial - Why Should I Learn Julia Programming Language
codebasics
Python Tutorial - 16. Exception Handling
codebasics
Julia Tutorial - 3. Complex and Rational Numbers
codebasics
Julia Tutorial - 4. Strings
codebasics
Python Tutorial - 17. Class and Objects
codebasics
Julia Tutorial - 5. Functions
codebasics
Julia Tutorial - 6. If Statement and Ternary Operator
codebasics
Julia Tutorial - 7. For While Loop
codebasics
Python Tutorial - 18. Inheritance
codebasics
Julia Tutorial - 8. begin and (;) Compound Expressions
codebasics
Python Tutorial - 12.1 - Install Python Module (using pip)
codebasics
Julia Tutorial - 9. Tasks (a.k.a. Generators or Coroutines)
codebasics
Julia Tutorial - 10. Exception Handling
codebasics
Python Tutorial - 19. Multiple Inheritance
codebasics
Python Tutorial - 20. Raise Exception And Finally
codebasics
Python Tutorial - 21. Iterators
codebasics
Python Tutorial - 22. Generators
codebasics
Python Tutorial - 23. List Set Dict Comprehensions
codebasics
Python Tutorial - 24. Sets and Frozen Sets
codebasics
Python Tutorial - 25. Command line argument processing using argparse
codebasics
Debugging Tips - What is bug and debugging?
codebasics
Debugging Tips - Conditional Breakpoint
codebasics
Debugging Tips - Watches and Call Stack
codebasics
Python Tutorial - 26. Multithreading - Introduction
codebasics
Git Tutorial 3: How To Install Git
codebasics
Git Tutorial 1: What is git / What is version control system?
codebasics
Git Tutorial 2 : What is Github? | github tutorial
codebasics
Git Tutorial 4: Basic Commands: add, commit, push
codebasics
Git Tutorial 5: Undoing/Reverting/Resetting code changes
codebasics
Git Tutorial 6: Branches (Create, Merge, Delete a branch)
codebasics
Git Github Tutorial 10: What is Pull Request?
codebasics
Git Tutorial 7: What is HEAD?
codebasics
Git Tutorial 9: Diff and Merge using meld
codebasics
Difference between Multiprocessing and Multithreading
codebasics
Python Tutorial - 27. Multiprocessing Introduction
codebasics
Python Tutorial - 28. Sharing Data Between Processes Using Array and Value
codebasics
Git Tutorial 8 - .gitignore file
codebasics
Python Tutorial - 29. Sharing Data Between Processes Using Multiprocessing Queue
codebasics
Python Tutorial - 30. Multiprocessing Lock
codebasics
Python Tutorial - 31. Multiprocessing Pool (Map Reduce)
codebasics
What is code?
codebasics
Python unit testing - pytest introduction
codebasics
Related AI Lessons
Chapters (4)
Explain why decorators needed?
3:52
What is a decorator?
4:18
create decorators
4:26
Call repper function
🎓
Tutor Explanation
DeepCamp AI