Decorators in Python - Advanced Python 13 - Programming Tutorial

Patrick Loeber · Beginner ·🛠️ AI Tools & Apps ·6y ago

Key Takeaways

The video tutorial covers the use of decorators in Python, including function decorators and class decorators, to extend the behavior of functions without modifying them. It demonstrates how to create and apply decorators, preserve original function metadata, and use decorators to implement various functionalities such as timing, debugging, and checking arguments.

Full Transcript

hi everybody welcome to your new Python tutorial today we're going to talk about decorators in Python decorators are a very powerful tool in Python and every advanced Python programmer should know it in this video and show you the concept behind decorators how you can write your own decorators the difference between function and class decorators and some typical use cases I promise you that once you have understood the concept it is not as difficult as it seems in the beginning and it might improve your Python knowledge a lot so let's start there are two different decorators function decorators and class decorators more common is the function decorator and it looks like this so you have a function call it def and let's say call it do something and does nothing in this case and above your function you have an @ sign and then some other function name so some decorate a function name let's say my decorator so this is how the decorator syntax looks and what this does a decorator is a function that takes another function as argument and extends the behavior of this function without explicitly modifying it so in other words it allows you to add new functionality to an existing function so in this case this function would be extended with the functionality of this decorator and in order to understand this concept we have to know that functions in Python are first-class objects this means that like any other object they can be defined inside another function passed as an argument to another function and even returned from other function so now let's have a closer look at the concept so let's say we want to we have a function and call it print name and this will simply print Alex and then we have a decorator function call it start and decorator and now as an argument it takes a function in inside our decorator function we have an inner function called and we call it wrapper so deaf rapper this is a wrapper function which which wraps our function so he inside this wrapper function we execute the function and then as I said I can extend the behavior so I can do something before and I can do something after it so before I say in this case simply print start and after it I want to print end and then after creating this inner wrapper function I also have to return it and now to apply this let's first of all simply let's execute the print name function so now if I run this it prints Alex and in order to apply the decorator I assign this print name function to now to our decorator function and as argument I take the print name function so now the print name function has this new functionality so now if I run this we will see that it prints start then execute the function and prints Alex and then it prints end and now the decorator function will do the same thing as this line so now if I write at start and decorator then I don't need this anymore so this now that's the same thing if I execute it now it will also print start Alex and end and now this is how we can extend the behavior of a function with a decorator so let's see what happens if a if our function has some arguments so let's say we have a function call it at 5 and this takes an argument and then it returns X plus 5 and now if I try to run this at 5 and this argument I give 10 now if I run this I will get a type error because our rapa takes zero positional arguments but one was given so here I need the same arguments as here and to fix this I can use the arcs and quarks I will talk about this in another video in more detail but basically with this syntax I can use as many arguments and keyword arguments as I want and now inside our wrapper function I also call this function with the arguments and keyword arguments so let's write it like this and now if I execute it then it works so this is how you apply arguments and now what about the return value so let's store this in a result so let's say result equals at five and then print the result now if I print this this will print none here and to fix this I also have to save the result of the function here and then return it from my inner wrapper function the return result and now if I run this it can print the result and now as a last thing what about the function identity so let's print the help function of at five the help information with this help function and also let's print the name of this function with this double underscore method now if I run this this will print that the help function wrapper and the function name is also wrapper so Python got confused now about the identity of this function so in order to fix this I can import func tools and here before my wrapper I apply also a decorator it's called func tools dot wraps func so this will now preserve the information of my used function so now if I run this I see that it now knows the help on function at 5 and also our function name is now again at 5 so this is all to complete the decorator func decorator syntax so this now is a template for a decorator that you can use for all your function decorator so let's say call it my decorator then you can do something before the function then you execute the function and then you can do something afterwards and then you return the result and return the wrapper so this is the template for a nice decorator and you can also have a look at this on my website Python - engineer calm yeah so now as we've seen here we see here a decorator that takes a function that takes an argument so decorators can also take arguments and what this bit means this is basically now two inner functions so an inner function within and in a function and to make this clearer we look at another example so let's say we have a function call it greet and then it takes a name and then inside it will print and now we use an F string and I've shown this before in another video about strings so you can say hello and then inside braces we use the name and now we use a decorator and call it repeat and give it an argument num x and set it to three so I want a repeat decorator that executes this function three times so how does this decorate a now look first of all we have the outer function repeat which also takes num x and then inside it takes our decorator function as we've seen it before so we have a decorator so define a decorator repeat and this takes a function and then inside here we have our wrapper and this takes arcs and marks and we decorate this with our funk tools dot raps decorator and then inside our wrapper I simply want to repeat this the number of times I've given here so I say four underscore because I don't need this four on the score in range num times and then I say result equals our function with the arcs and the quarks and then I return the result then I return the wrapper and then I return the decorator so now if I execute greet Alex then this will be executed the number of times I've given here so now if I say executed four times so this is how the concept behind decorate us with arguments work and now let's also talk about nested decorators so you can stack decorators on top of each other so you can let's say we have a function and call it let me copy this year so let's we have a function say hello which gets a name then it prints a greeting and returns the greeting and now we can debug this we can decorate this with our start and decorator as we've seen it before now let me copy this here inside this is our start and decorator which will print start and end after our function and we also decorated this with a second decorator and call it D Bach and now let me copy this debug decorator in here so this debug decorator extracts the name and the arguments and the keyword arguments and then it prints the information of this function it executes the function and then it also prints the information about the return value so this will basically print some more information about this function and so now if I apply multiple decorators to a function they will be executed in the order they are listed so this means now if I say if I execute say hello Alex this will first of all execute the debug function and then inside the debug function it will execute the start and decorate a function and then inside this function it will execute the say hello function so now if I run this we will see that first of all it prints calling say hello this is from my debug rapa then it prints start from the start and decorator then it prints hello Alex then end and then again I'm here I am prints the function name and the return value hello Alex so this is how you can apply multiple decorators and now it's a last thing let's talk about class decorators so instead of a function decorator you can also define a class decorator so let's say we have our function say hello and then it simply prints hello and I want to decorate this with a class decorator and I call this count calls so class decorators do the same thing as function decorators but they are typically used if we want to maintain and update a state so in this example I want to keep track of how many times I have executed this function so let's create a class call it count calls and this has a init method and it takes self of course and then it takes the function just like the decorator function and then inside the init I will save the function as class variable or as member variable and I say self func equals func and then I will also create a state and I call this self dot num calls so and this is zero in the beginning so I want to keep track of how many times this got executed and now in order to write a class decorator I have to implement the call method so this also takes self then the arcs and the quarks and this is the same as the inner function in our function decorator and now sorry this also has trailing double underscores and now the call method allows me to execute a object of this class just like a function so let's as an example let's just print hi there here and now let's say I create a object of this class called CC equals count calls and this takes a function here so in this example I just use none and now since I've implemented this call method I can say CC and execute this as a function so now if I run this it prints hi there so in our example I don't want to print hi there so what I want to do now I want to update the state so I say self dot none calls plus equals 1 then I want to print the number of calls so I print this is executed self dot num sorry self num calls times and then now this is my then I also have to execute and return the function so I say return self dot func and now I call the function with all the arguments and the keyword arguments and now if I say if I run this and ice say say hello then oh sorry itself gnome calls now if I run this then I will see this is executed one times and now if I run this again then I will see now this is executed two times so here I can keep track of how many times this is executed so this is how you can implement class decorators and now let's talk about some typical use cases of decorators so for example you can implement a time a decorator to calculate the execution time of a function you can use a debug decorator like you've seen before to print out some more information about the code function and its arguments you can use a check decorator to check if the arguments who fill some requirements and the depth the behavior accordingly you can register functions like plugins with decorators you can cache the return values or you can add information or update the state so that's all about working with decorators I hope you enjoyed this tutorial and now feel comfortable working with them and see you in the next tutorial where we talk about generators in Python

Original Description

Decorators in Python - Advanced Python 13 - Programming Tutorial In this Python Advanced Tutorial, we will be learning about Decorators in Python. A decorator is a function that takes another function and extends the behavior of this function without explicitly modifying it. It's a very powerful tool for advanced programmers. In this tutorial, I show you the concept behind decorators, how you can write your own decorators, the difference between function and class decorators, and some typical use cases. ~~~~~~~~~~~~~~ GREAT PLUGINS FOR YOUR CODE EDITOR ~~~~~~~~~~~~~~ ✅ Write cleaner code with Sourcery: https://sourcery.ai/?utm_source=youtube&utm_campaign=pythonengineer * 📚 Get my FREE NumPy Handbook: https://www.python-engineer.com/numpybook 📓 Notebooks available on Patreon: https://www.patreon.com/patrickloeber ⭐ Join Our Discord : https://discord.gg/FHMg9tKFSN A written Tutorial can be found here: https://www.python-engineer.com/courses/advancedpython/13-decorators/ You can find me here: Website: https://www.python-engineer.com Twitter: https://twitter.com/patloeber GitHub: https://github.com/patrickloeber #Python ---------------------------------------------------------------------------------------------------------- * This is a sponsored link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you so much for the support! 🙏
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Patrick Loeber · Patrick Loeber · 13 of 60

1 Lists in Python - Advanced Python 01 - Programming Tutorial
Lists in Python - Advanced Python 01 - Programming Tutorial
Patrick Loeber
2 Tuples in Python - Advanced Python 02 - Programming Tutorial
Tuples in Python - Advanced Python 02 - Programming Tutorial
Patrick Loeber
3 Dictionaries in Python - Advanced Python 03 - Programming Tutorial
Dictionaries in Python - Advanced Python 03 - Programming Tutorial
Patrick Loeber
4 Sets in Python - Advanced Python 04 - Programming Tutorial
Sets in Python - Advanced Python 04 - Programming Tutorial
Patrick Loeber
5 Strings in Python - Advanced Python 05 - Programming Tutorial
Strings in Python - Advanced Python 05 - Programming Tutorial
Patrick Loeber
6 Collections in Python - Advanced Python 06 - Programming Tutorial
Collections in Python - Advanced Python 06 - Programming Tutorial
Patrick Loeber
7 Itertools in Python - Advanced Python 07 - Programming Tutorial
Itertools in Python - Advanced Python 07 - Programming Tutorial
Patrick Loeber
8 Lambda in Python - Advanced Python 08 - Programming Tutorial - Map Filter Reduce
Lambda in Python - Advanced Python 08 - Programming Tutorial - Map Filter Reduce
Patrick Loeber
9 Exceptions in Python - Advanced Python 09 - Programming Tutorial
Exceptions in Python - Advanced Python 09 - Programming Tutorial
Patrick Loeber
10 Logging in Python - Advanced Python 10 - Programming Tutorial
Logging in Python - Advanced Python 10 - Programming Tutorial
Patrick Loeber
11 JSON in Python - Advanced Python 11 - Programming Tutorial
JSON in Python - Advanced Python 11 - Programming Tutorial
Patrick Loeber
12 Random Numbers in Python - Advanced Python 12 - Programming Tutorial
Random Numbers in Python - Advanced Python 12 - Programming Tutorial
Patrick Loeber
Decorators in Python - Advanced Python 13 - Programming Tutorial
Decorators in Python - Advanced Python 13 - Programming Tutorial
Patrick Loeber
14 Generators in Python - Advanced Python 14 - Programming Tutorial
Generators in Python - Advanced Python 14 - Programming Tutorial
Patrick Loeber
15 Threading vs Multiprocessing in Python - Advanced Python 15 - Programming Tutorial
Threading vs Multiprocessing in Python - Advanced Python 15 - Programming Tutorial
Patrick Loeber
16 Threading in Python - Advanced Python 16 - Programming Tutorial
Threading in Python - Advanced Python 16 - Programming Tutorial
Patrick Loeber
17 Multiprocessing in Python - Advanced Python 17 - Programming Tutorial
Multiprocessing in Python - Advanced Python 17 - Programming Tutorial
Patrick Loeber
18 Function arguments in detail - Advanced Python 18 - Programming Tutorial
Function arguments in detail - Advanced Python 18 - Programming Tutorial
Patrick Loeber
19 The asterisk (*) operator in Python - Advanced Python 19 - Programming Tutorial
The asterisk (*) operator in Python - Advanced Python 19 - Programming Tutorial
Patrick Loeber
20 Shallow vs Deep Copying in Python - Advanced Python 20 - Programming Tutorial
Shallow vs Deep Copying in Python - Advanced Python 20 - Programming Tutorial
Patrick Loeber
21 Context Managers in Python - Advanced Python 21 - Programming Tutorial
Context Managers in Python - Advanced Python 21 - Programming Tutorial
Patrick Loeber
22 KNN (K Nearest Neighbors) in Python - Machine Learning From Scratch 01 - Python Tutorial
KNN (K Nearest Neighbors) in Python - Machine Learning From Scratch 01 - Python Tutorial
Patrick Loeber
23 Linear Regression in Python - Machine Learning From Scratch 02 - Python Tutorial
Linear Regression in Python - Machine Learning From Scratch 02 - Python Tutorial
Patrick Loeber
24 Logistic Regression in Python - Machine Learning From Scratch 03 - Python Tutorial
Logistic Regression in Python - Machine Learning From Scratch 03 - Python Tutorial
Patrick Loeber
25 Linear and Logistic Regression in 60 lines of Python - Machine Learning From Scratch 04
Linear and Logistic Regression in 60 lines of Python - Machine Learning From Scratch 04
Patrick Loeber
26 Naive Bayes in Python - Machine Learning From Scratch 05 - Python Tutorial
Naive Bayes in Python - Machine Learning From Scratch 05 - Python Tutorial
Patrick Loeber
27 Perceptron in Python - Machine Learning From Scratch 06 - Python Tutorial
Perceptron in Python - Machine Learning From Scratch 06 - Python Tutorial
Patrick Loeber
28 SVM (Support Vector Machine) in Python - Machine Learning From Scratch 07 - Python Tutorial
SVM (Support Vector Machine) in Python - Machine Learning From Scratch 07 - Python Tutorial
Patrick Loeber
29 Decision Tree in Python Part 1/2 - Machine Learning From Scratch 08 - Python Tutorial
Decision Tree in Python Part 1/2 - Machine Learning From Scratch 08 - Python Tutorial
Patrick Loeber
30 Decision Tree in Python Part 2/2 - Machine Learning From Scratch 09 - Python Tutorial
Decision Tree in Python Part 2/2 - Machine Learning From Scratch 09 - Python Tutorial
Patrick Loeber
31 Random Forest in Python - Machine Learning From Scratch 10 - Python Tutorial
Random Forest in Python - Machine Learning From Scratch 10 - Python Tutorial
Patrick Loeber
32 PCA (Principal Component Analysis) in Python - Machine Learning From Scratch 11 - Python Tutorial
PCA (Principal Component Analysis) in Python - Machine Learning From Scratch 11 - Python Tutorial
Patrick Loeber
33 K-Means Clustering in Python - Machine Learning From Scratch 12 - Python Tutorial
K-Means Clustering in Python - Machine Learning From Scratch 12 - Python Tutorial
Patrick Loeber
34 Anaconda Tutorial - Installation and Basic Commands
Anaconda Tutorial - Installation and Basic Commands
Patrick Loeber
35 PyTorch Tutorial 01 - Installation
PyTorch Tutorial 01 - Installation
Patrick Loeber
36 PyTorch Tutorial 02 - Tensor Basics
PyTorch Tutorial 02 - Tensor Basics
Patrick Loeber
37 PyTorch Tutorial 03 - Gradient Calculation With Autograd
PyTorch Tutorial 03 - Gradient Calculation With Autograd
Patrick Loeber
38 PyTorch Tutorial 04 - Backpropagation - Theory With Example
PyTorch Tutorial 04 - Backpropagation - Theory With Example
Patrick Loeber
39 PyTorch Tutorial 05 - Gradient Descent with Autograd and Backpropagation
PyTorch Tutorial 05 - Gradient Descent with Autograd and Backpropagation
Patrick Loeber
40 PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer
PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer
Patrick Loeber
41 PyTorch Tutorial 07 - Linear Regression
PyTorch Tutorial 07 - Linear Regression
Patrick Loeber
42 PyTorch Tutorial 08 - Logistic Regression
PyTorch Tutorial 08 - Logistic Regression
Patrick Loeber
43 PyTorch Tutorial 09 - Dataset and DataLoader - Batch Training
PyTorch Tutorial 09 - Dataset and DataLoader - Batch Training
Patrick Loeber
44 PyTorch Tutorial 10 - Dataset Transforms
PyTorch Tutorial 10 - Dataset Transforms
Patrick Loeber
45 Download Images With Python Automatically - Python Web Scraping Tutorial
Download Images With Python Automatically - Python Web Scraping Tutorial
Patrick Loeber
46 PyTorch Tutorial 11 - Softmax and Cross Entropy
PyTorch Tutorial 11 - Softmax and Cross Entropy
Patrick Loeber
47 Select Movies with Python - Web Scraping Tutorial
Select Movies with Python - Web Scraping Tutorial
Patrick Loeber
48 PyTorch Tutorial 12 - Activation Functions
PyTorch Tutorial 12 - Activation Functions
Patrick Loeber
49 List Comprehension in Python - A Python Feature You MUST KNOW - Python Tutorial
List Comprehension in Python - A Python Feature You MUST KNOW - Python Tutorial
Patrick Loeber
50 PyTorch Tutorial 13 - Feed-Forward Neural Network
PyTorch Tutorial 13 - Feed-Forward Neural Network
Patrick Loeber
51 How To Add A Progress Bar In Python With Just One Line - Python Tutorial
How To Add A Progress Bar In Python With Just One Line - Python Tutorial
Patrick Loeber
52 PyTorch Tutorial 14 - Convolutional Neural Network (CNN)
PyTorch Tutorial 14 - Convolutional Neural Network (CNN)
Patrick Loeber
53 The Walrus Operator - New in Python 3.8 - Python Tutorial
The Walrus Operator - New in Python 3.8 - Python Tutorial
Patrick Loeber
54 PyTorch Tutorial 15 - Transfer Learning
PyTorch Tutorial 15 - Transfer Learning
Patrick Loeber
55 YouTube Data API Tutorial with Python - Analyze Channel Statistics - Part 1
YouTube Data API Tutorial with Python - Analyze Channel Statistics - Part 1
Patrick Loeber
56 YouTube Data API Tutorial with Python - Find Channel Videos - Part 2
YouTube Data API Tutorial with Python - Find Channel Videos - Part 2
Patrick Loeber
57 YouTube Data API Tutorial with Python - Get Video Statistics - Part 3
YouTube Data API Tutorial with Python - Get Video Statistics - Part 3
Patrick Loeber
58 YouTube Data API Tutorial with Python - Analyze the Data - Part 4
YouTube Data API Tutorial with Python - Analyze the Data - Part 4
Patrick Loeber
59 AdaBoost in Python - Machine Learning From Scratch 13 - Python Tutorial
AdaBoost in Python - Machine Learning From Scratch 13 - Python Tutorial
Patrick Loeber
60 Ultimate FREE Study Guide for Machine Learning and Deep Learning
Ultimate FREE Study Guide for Machine Learning and Deep Learning
Patrick Loeber

This video tutorial teaches how to use decorators in Python to extend the behavior of functions without modifying them. It covers function decorators, class decorators, and how to use them to implement various functionalities. By the end of this tutorial, you will be able to create and apply decorators to functions, preserve original function metadata, and use decorators to implement timing, debugging, and checking arguments.

Key Takeaways
  1. Create a decorator function
  2. Define a wrapper function inside the decorator function
  3. Apply the decorator to a function using the @ symbol
  4. Use functools.wraps to preserve the original function's metadata
  5. Decorate a function with a decorator that takes an argument
  6. Use a loop inside the decorator function to repeat a function multiple times
  7. Decorate a function with multiple decorators to stack them together
💡 Decorators are a powerful tool in Python that can extend the behavior of functions without modifying them, and they can be used to implement various functionalities such as timing, debugging, and checking arguments.

Related AI Lessons

Up next
I Asked ChatGPT to Apply to 500 Jobs (8 Interviews in 48 Hours)
Sabrina Ramonov 🍄
Watch →