Python Decorators Tutorial

codebasics · Beginner ·🛠️ AI Tools & Apps ·9y ago

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 Python Tutorial - 1. Install python on windows
Python Tutorial - 1. Install python on windows
codebasics
2 Python Tutorial - 2. Variables
Python Tutorial - 2. Variables
codebasics
3 Python Tutorial - 3. Numbers
Python Tutorial - 3. Numbers
codebasics
4 Python Tutorial - 4. Strings
Python Tutorial - 4. Strings
codebasics
5 Python Tutorial - 5. Lists
Python Tutorial - 5. Lists
codebasics
6 Python Tutorial - 6. Install PyCharm on Windows
Python Tutorial - 6. Install PyCharm on Windows
codebasics
7 PyCharm Tutorial - 7. Debug python code using PyCharm
PyCharm Tutorial - 7. Debug python code using PyCharm
codebasics
8 Python Tutorial -  8. If Statement
Python Tutorial - 8. If Statement
codebasics
9 Python Tutorial - 9. For loop
Python Tutorial - 9. For loop
codebasics
10 Python Tutorial -  10. Functions
Python Tutorial - 10. Functions
codebasics
11 Python Tutorial - 11. Dictionaries and Tuples
Python Tutorial - 11. Dictionaries and Tuples
codebasics
12 Python Tutorial - 12. Modules
Python Tutorial - 12. Modules
codebasics
13 Python Tutorial - 13. Reading/Writing Files
Python Tutorial - 13. Reading/Writing Files
codebasics
14 How to install Julia on Windows
How to install Julia on Windows
codebasics
15 Python Tutorial - 14. Working With JSON
Python Tutorial - 14. Working With JSON
codebasics
16 Julia Tutorial - 1. Variables
Julia Tutorial - 1. Variables
codebasics
17 Julia Tutorial - 2. Numbers
Julia Tutorial - 2. Numbers
codebasics
18 Python Tutorial - 15. if __name__ == "__main__"
Python Tutorial - 15. if __name__ == "__main__"
codebasics
19 Julia Tutorial - Why Should I Learn Julia Programming Language
Julia Tutorial - Why Should I Learn Julia Programming Language
codebasics
20 Python Tutorial  - 16. Exception Handling
Python Tutorial - 16. Exception Handling
codebasics
21 Julia Tutorial - 3. Complex and Rational Numbers
Julia Tutorial - 3. Complex and Rational Numbers
codebasics
22 Julia Tutorial - 4. Strings
Julia Tutorial - 4. Strings
codebasics
23 Python Tutorial -  17. Class and Objects
Python Tutorial - 17. Class and Objects
codebasics
24 Julia Tutorial - 5. Functions
Julia Tutorial - 5. Functions
codebasics
25 Julia Tutorial - 6. If Statement and Ternary Operator
Julia Tutorial - 6. If Statement and Ternary Operator
codebasics
26 Julia Tutorial - 7. For While Loop
Julia Tutorial - 7. For While Loop
codebasics
27 Python Tutorial  - 18. Inheritance
Python Tutorial - 18. Inheritance
codebasics
28 Julia Tutorial - 8. begin and (;) Compound Expressions
Julia Tutorial - 8. begin and (;) Compound Expressions
codebasics
29 Python Tutorial - 12.1 - Install Python Module (using pip)
Python Tutorial - 12.1 - Install Python Module (using pip)
codebasics
30 Julia Tutorial - 9. Tasks (a.k.a. Generators or Coroutines)
Julia Tutorial - 9. Tasks (a.k.a. Generators or Coroutines)
codebasics
31 Julia Tutorial - 10. Exception Handling
Julia Tutorial - 10. Exception Handling
codebasics
32 Python Tutorial  - 19. Multiple Inheritance
Python Tutorial - 19. Multiple Inheritance
codebasics
33 Python Tutorial - 20. Raise Exception And Finally
Python Tutorial - 20. Raise Exception And Finally
codebasics
34 Python Tutorial - 21. Iterators
Python Tutorial - 21. Iterators
codebasics
35 Python Tutorial - 22. Generators
Python Tutorial - 22. Generators
codebasics
36 Python Tutorial - 23. List Set Dict Comprehensions
Python Tutorial - 23. List Set Dict Comprehensions
codebasics
37 Python Tutorial - 24. Sets and Frozen Sets
Python Tutorial - 24. Sets and Frozen Sets
codebasics
38 Python Tutorial - 25. Command line argument processing using argparse
Python Tutorial - 25. Command line argument processing using argparse
codebasics
39 Debugging Tips - What is bug and debugging?
Debugging Tips - What is bug and debugging?
codebasics
40 Debugging Tips - Conditional Breakpoint
Debugging Tips - Conditional Breakpoint
codebasics
41 Debugging Tips - Watches and Call Stack
Debugging Tips - Watches and Call Stack
codebasics
42 Python Tutorial - 26. Multithreading - Introduction
Python Tutorial - 26. Multithreading - Introduction
codebasics
43 Git Tutorial 3:  How To Install Git
Git Tutorial 3: How To Install Git
codebasics
44 Git Tutorial 1: What is git / What is version control system?
Git Tutorial 1: What is git / What is version control system?
codebasics
45 Git Tutorial 2 : What is Github? | github tutorial
Git Tutorial 2 : What is Github? | github tutorial
codebasics
46 Git Tutorial 4: Basic Commands: add, commit, push
Git Tutorial 4: Basic Commands: add, commit, push
codebasics
47 Git Tutorial 5: Undoing/Reverting/Resetting code changes
Git Tutorial 5: Undoing/Reverting/Resetting code changes
codebasics
48 Git Tutorial 6: Branches (Create, Merge, Delete a branch)
Git Tutorial 6: Branches (Create, Merge, Delete a branch)
codebasics
49 Git Github Tutorial 10: What is Pull Request?
Git Github Tutorial 10: What is Pull Request?
codebasics
50 Git Tutorial 7: What is HEAD?
Git Tutorial 7: What is HEAD?
codebasics
51 Git Tutorial 9: Diff and Merge using meld
Git Tutorial 9: Diff and Merge using meld
codebasics
52 Difference between Multiprocessing and Multithreading
Difference between Multiprocessing and Multithreading
codebasics
53 Python Tutorial - 27. Multiprocessing Introduction
Python Tutorial - 27. Multiprocessing Introduction
codebasics
54 Python Tutorial - 28. Sharing Data Between Processes Using Array and Value
Python Tutorial - 28. Sharing Data Between Processes Using Array and Value
codebasics
55 Git Tutorial 8 - .gitignore file
Git Tutorial 8 - .gitignore file
codebasics
56 Python Tutorial - 29. Sharing Data Between Processes Using Multiprocessing Queue
Python Tutorial - 29. Sharing Data Between Processes Using Multiprocessing Queue
codebasics
57 Python Tutorial - 30. Multiprocessing Lock
Python Tutorial - 30. Multiprocessing Lock
codebasics
58 Python Tutorial - 31. Multiprocessing Pool (Map Reduce)
Python Tutorial - 31. Multiprocessing Pool (Map Reduce)
codebasics
59 What is code?
What is code?
codebasics
60 Python unit testing - pytest introduction
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
Up next
How to Open HPL Files (HP-GL Plotter)
File Extension Geeks
Watch →