Expert Python Tutorial #4 - Decorators
Skills:
LLM Foundations85%
Key Takeaways
This video tutorial covers Python decorators, which allow modifying the behavior of a function without changing its code, using tools such as Python and time module.
Full Transcript
hello everybody and welcome back to our expert Python tutorial so in today's video we are going to be talking about decorators which are a pretty cool and useful tool they're not super complex but essentially they allow us to modify the behavior of a function without actually changing any of its code now this is useful because sometimes you want to be able to add and remove decorators while debugging a function or maybe you want to change the behavior of all of your functions and rather than going in and changing all of the code you could create a decorator which will allow you to simply you know use one line of code to change the behavior of all of these different functions so I'll show you how this works and what a decorator actually is to start by just going through a bit of a kind of recap of how Python passes objects around and why we can actually even use decorator a quick reminder before we get started that kite is the sponsor of this series kite is the best AI autocomplete for Python on the market and you can get it for free in the link in the description it integrates with the all the popular IDs and text editors so subline vs code Adam them you name it chances are kite is you know compatible with that again you can download that from the link in the description so the first thing I'm gonna do is we're gonna create a function called func now what I want to do is just show you that if this function takes a string I can actually return another function in here that does something with this argument and we've seen this before in the previous expert Python tutorials but I want to just make this very clear on how this works so I'm gonna call this function a wrapper because it's inside of this function it's not gonna take anything as an argument and what I'm simply gonna do in here is a print started print string and print ended like that on the Bill of capital and I guess actually this string sorry does not need to be in a string needs to be like that so we print the variable and then what I'm going to do here is simply return the wrapper function like that so if I do this now what happens if i say x equals func like that and i put in my string let's say hello and i run this program you can see we get started hello and end it now the reason that happened is because we returned here the wrapper being called write these two brackets but if i remove this and I do this now nothing happens so what we've actually done if I print out the value of x as you see we store a function in here that was returned from this function which is actually equal to this and then if we wanted to call this function we could put our little braces like that and here we go we get started hello and ended so just want to show you that this is possible and the reason this is possible is because functions in Python are objects which means that we can pass them around we can throw them around our program and you can see up here this is the location of the object you know function wrapper from func dot locals okay so now that we understand that let's bring it up a little notch and see what happens if we actually instead of just passing a string in here pass another function so I define a function function I'll call it func - like that and all we'll do in here is just print or something will say I am func - why not I'll get rid of this and now rather than passing a string in here why don't we actually just call some function so let's put f in here let's put I don't want func - I just want F let's call whatever function is called so we'll do print started call whatever function was in here and then print ended and then return this function so let's see how this works so now if I can move this down a bit let's say x equals funk funk - let's print X and then let's call X so what we're doing here for anyone that's confused is we've created this function which accepts a function as an argument writer as a parameter then what we do in here is we define a function that prints started calls whatever function was passed in prints ended and then returns this function so this is not actually gonna do anything until it is called so when we return this we'll store it in a variable X and then when we want to use this interior function here we call it with this write the X and the brackets so let's have a look at how this works control B and you can see started I am func - ended function func wrapper locals right and the idea here is that I can do the same thing with say func 3 right if I print let's say I am funk 3 like that now rather than passing funk - I can pass funk 3 and we can see now we get the same thing happening except funk 3 and in fact we could do it you know I would say y equals funk funk - and then we can do the same thing and just call lie down here and now both of them are going to work and they're both going to be different so started I am funk 3 started I'm fun to end so with this in mind we can start looking at kind of what a decorator is now almost but I just want to show you a way that let's say you know this function right here which we're gonna call our decorator we don't want to have to do this weird call right where we use our decorator function to call function 3 we just want to call function 3 and have it do this behavior and you know do whatever function 3 is right how do we get that to work how did we get that to happen where rather than me having to call funk and pass funk 3 and call funk and pass funk - how can we do this another way well what I can actually do is kind of a cool sneaky line here Python where I do this I say funk 3 is equal to funk at funk 3 now this seems like a weird line of code but essentially what this is going to allow us to do now is rather than having to call function and pass funk 3 in we can actually use funk 3 which is a variable now which stores the function that is returned from the call of funk with function 3 which means that if we call funk 3 like that then what's gonna happen is it's gonna run this function that was created from this call so this is a way that we can kind of change that behavior we can say okay so funk 3 I always brought want this whatever's inside this wrapper function to happen whenever I call it so all I need to do to define that is write this line of code and now every time I call funk 3 from anywhere in my program it'll do this and if we run this we can see that happens and that works fine then we can do the same thing with funk - yeah fun - equals funk funk - and that will call fun - like that's and we can see that it works for both of them so this is where we now get into the concept of a decorator things are gonna get a little bit more complicated but now all I'm gonna show you is what a decorator does versus what we've done so this kind of line of code here is weird right like it's not something you really want to write you don't really know where to put it it's like just not ideal to have to write this line of code so python has thought of this for us and what they've introduced is a syntax that essentially allows us to do this just in a better way and all it is is using this @ sign and putting the name of your decorated function so like that just on top so now this line here pretty much just replaces this line like they're the exact identical copy they do the same thing this just looks a little bit nicer and it's a little bit easier to understand what's happening when you have you know there's a decorator syntax above the function and you can actually decorate your function with more than one decorator if you want we're not going to talk about that right now but that's something to note so pretty much to replace these lines of code all I have to do is put at the name of the function that I want to run before right and then now if I do func 3 and func 2 we can see we get the same thing so we get started I'm func three ended started I'm Fung two ended so this is how this works so whenever you're creating a decorator function you need to kind of implement this wrapper functionality where the first thing takes the function itself and the second function here while this just takes the or what is this this creates the function that's going to be called when this is returned right or when you actually call this function so it's actually you're changing your SEC func to is now gonna be equal to whatever this is and usually inside of here you're gonna use the function now there's a lot of problems that I'm sure some of you can think of here so what happens if I say func to takes an argument X and instead of saying I am func - all it does is just print out X what happens now well if I run this and I even let's give it our email let's get 5 here you can see we're getting an error right and the reason we're getting arond this huge error was a sec wrapper take zero positional arguments but one was given so the issue is that when we actually call func to what we're actually going to be calling from this line of code is this wrapper function so this wrapper function needs to have the same amount of arguments that function2 has so how can we do that how can we fix that well we could just put an X here like this right and then less comments out func 3 let's run this oh sorry my bad we gotta throw an X in here that was what the issue is before so we have our X's there and then this works right so I put an X in the wrapper I put an X here which means that when I call this X will be passed to this wrapper X and then we can use that to call the function and that's totally fine but what happens now when I want to use func 3 and func 3 doesn't take any arguments but this takes arguments the whole point of decorators is to be able to use this on multiple functions and we get missing one required positional argument X func 3 there's an issue you know things are happening so what what do we do here how do we fix this well this is where we use what we call the unpack operator I believe it's splat operator something but essentially you can put star args star star kwargs like this and what this will allow you to do is accept any number of positional or keyword arguments so essentially this says okay we don't know how many arguments are gonna be coming in here there could be an infinite amount so rather than just trying to guess or figure it out or write a different wrapper function for every single amount what we'll do is simply write star args starts our kwargs which tells us accept all the arguments that are passed in accept all the keyword arguments and what we can actually do is simply pass whatever these are to this function so let's do this here star star quacks so now what's gonna happen is any arguments passed in will just automatically pass to F same with kwargs and if there's none we just won't pass anything so this kind of handles any amount of arguments and now we'll see that when we run this we don't get any error and this works fine for any number of arguments so even if I were to add you know X Y in here something like that and then we call this with like 5 6 and run that still same thing this is working doesn't matter how many arguments we have we're perfectly fine okay so that's good but what happens when we return a value from function two well what happens out so let's say x equals print X and right now so we can see that we're returning Y from function to right but if I call this and I print X we don't get Y returned to us so how can we fix this right so what we actually need to do is since we're calling the actual function here inside of the wrapper we need to store the return value going to store that as our V so that I can return it at the end of this wrapper function so since this wrapper function is returned from here this could return a value as well and well we don't want to return immediately so like I could just write the line return F like that and that would work fine but we want to do something after the function is called so to you know solve this we do our B and then we can return our V so store the return value this function return at the end and now if I print this you can see that we get our return value of 6 so that is how we return value so that is how we pass in different amounts of parameters and now I'm just going to show you a few actual useful on decorator functions that you might want to use so you're probably looking at me like well what's the point of this right now like why do we have this well a good example is say you want to validate input say you want to have a bunch of functions that accept some numeric input and that numeric input is always going to be between the value 1 and 10 right rather than checking the parameters every single time inside of your function what you could do is you can use a decorator that checks them for you right and then all you would have to do every single time you want to validate that your input is correct is throw a decorator over top of your function that says validate input or whatever it's called write the appropriate code inside of a decorated function of these kind of functions like this and then you're good to go so that is kind of the idea behind decorators that you can modify the behavior of function add functionality to it without modifying the code and sometimes you don't want to touch the code of a function because you want to make sure that you're not breaking anything you don't know how it's been written but you want to add something on top for example maybe timing how fast the function runs and this is a very common example I'll show you this as kind of our last example to using decorators so yeah we'll do a timing one so essentially if I want a time how long a function takes to run every single time right then I can create a timer decorator so you know actually let's do it from the start let's erase all this and do one from the beginning so I'm gonna say define timer which is the name my decorator it's gonna take in a function will define a wrapper this will take star args star star quarks like that again quark stands for keyword arguments what we're gonna do here is start by importing time we're gonna say let's say start equals time dot time like that and then we'll just print started actually we could do something else let's do this let's say our B equals func like that and then let's say end or will s will say total equals time dot time - start and then we'll print time like that and we can put total and then we will return our V and return wrapper like that oops I did not mean for those okay so now that we have that let's create a function let's just say defiant test and then here we're just gonna say for others who are in range thousand let's just say pass and there we go so now if I want to decorate this function I'd say at timer and what this will allow me to do now is when I run this function have it tell me how long this took to run so let's go ahead and just actually call test like that and see it ran in 0.0 seconds so I guess this rounded for us but I guess and what I be able to do this make it take any longer if I add any more 0s there so we can see that is how much time this function took to run and if I wanted to add timer on another function well then I could do another one to say test two like that and we can even just say time dot sleep or why is my capitals on two seconds and we'll decorate this one with at timer as well and now when we call test two and we run this give it a second and we should see that this takes 2.01 seconds so this is how decorators work again useful when you want modify the behavior of a function without actually touching it without changing it you can add other decorators on top of an existing decorator I had urged you to see you know how that actually works how you'd be able to do that you can test that out for yourself but for now that's pretty much it and a really useful example of decorators is a timer decorator when you're debugging you want to check what is really slowing down or how long something's taking another good example is having a logging decorator so having a decorator that essentially logs the calling of functions or what's happening in the program that's a good one to add here and then obviously validating input and checking return values and stuff like that is always a good example of one you might want to use decorator so with that being said I hope you guys enjoyed if you have any questions as always leave them down below and with that being said I will see you in the next expert Python tutorial series
Original Description
In this video I'll be discussing python decorators. Decorators are a way to modify the behavior of a function without changing any of it's code. Decorators have many different use cases but are typically used when minor changes need to be made to many different functions.
⭐️ Thanks to Kite for sponsoring this video! Download the best AI automcolplete for python programming for free: https://kite.com/download/?utm_medium=referral&utm_source=youtube&utm_campaign=techwithtim&utm_content=expert-python-4
Playlist: https://www.youtube.com/watch?v=mclfteWlT2Q&list=PLzMcBGfZo4-kwmIcMDdXSuy_wSqtU-xDP
◾◾◾◾◾
💻 Enroll in The Fundamentals of Programming w/ Python
https://tech-with-tim.teachable.com/p/the-fundamentals-of-programming-with-python
📸 Instagram: https://www.instagram.com/tech_with_tim
🌎 Website https://techwithtim.net
📱 Twitter: https://twitter.com/TechWithTimm
⭐ Discord: https://discord.gg/pr2k55t
📝 LinkedIn: https://www.linkedin.com/in/tim-ruscica-82631b179/
📂 GitHub: https://github.com/techwithtim
🔊 Podcast: https://anchor.fm/tech-with-tim
💵 One-Time Donations: https://www.paypal.com/donate/?token=m_JfrPK7DsK4PLk0CxNnv4VPutjqSldorAmgQIQnMozUwwQw93vdul-yhU06IwAuig15uG&country.x=CA&locale.x=
💰 Patreon: https://www.patreon.com/techwithtim
◾◾◾◾◾◾
⚡ Please leave a LIKE and SUBSCRIBE for more content! ⚡
⭐ Tags ⭐
- Tech With Tim
- Python Tutorials
- Decorators Python
- Python Decorators Tutorial
- Decorators Tutorial Python
⭐ Hashtags ⭐
#Python #ExpertPython
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Tech With Tim · Tech With Tim · 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
A* Path Finding Algorithm(Visualization)
Tech With Tim
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
Python Programming Tutorial #3 - Conditions
Tech With Tim
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
Python Programming Tutorial #6 - For Loops
Tech With Tim
Python Programming Tutorial #7 - While Loops
Tech With Tim
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
Python Programming Tutorial #10 - String Methods
Tech With Tim
How to Overclock a NVIDIA GPU
Tech With Tim
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
Python Programming Tutorial #12 - Functions
Tech With Tim
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
Cool VBS Script to Prank Your Friends!
Tech With Tim
How to Overclock an AMD GPU
Tech With Tim
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
Recursion and Memoization Tutorial Python
Tech With Tim
Ethereum Mining Rig - Hardware Guide
Tech With Tim
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
How to Install Pygame (Windows 8/10)
Tech With Tim
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
Linear Search Algorithm - Python Example and Code
Tech With Tim
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
Binary Search Algorithm - Python Example & Code
Tech With Tim
Pygame Tutorial #5 - Projectiles
Tech With Tim
Pygame Game - Mini Golf
Tech With Tim
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
Pygame Tutorial #6 - Enemies
Tech With Tim
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
How to Create A Message Box in Python - Tkinter
Tech With Tim
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim
More on: LLM Foundations
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
Claude AI vs ChatGPT: Which One Is Actually Better in 2026?
Medium · AI
Claude AI vs ChatGPT: Which One Is Actually Better in 2026?
Medium · Programming
IntelliBooks: Classic RAG vs Graph RAG vs Agentic RAG – Choosing the Right AI Retrieval Architecture for Enterprise AI
Dev.to AI
Fluid, natural voice translation with Gemini 3.5 Live Translate
Dev.to AI
🎓
Tutor Explanation
DeepCamp AI