But it barely scratches a surface. Decorators can take also args and kwargs, there are functools for keeping a function name and signature the same. Overall decorators are much harder than this
Decorators are one of the many beautiful layers of Python. My favorite practical usage was a decorator that allows me to keep a database connection open and automatically rollback in case of an error.
@@0xdani000you would call the function with the decorator in some way to establish the database connection outside of the function to keeo the connection if the function has a problem
@@ferrumignis because if there is no wrapper function within the decorator, then the function f will get asigned to the result of f, which will make f no longer a callable function. Basically, if no wrapper is within the decorator f, f = my_decorator(f) will turn into f = f()
@@SpaghettDevcan you tell where in program behind the scene this line f=my_decorator(f) happens. I am still confused. Also what about when do_this() is called? Thanks
I first learned decorators when writing Ruby code a long time ago and still don't like them because they make code less readable. But, like ternary operators, we all still use them 😂
Jeez. Decorator had been just a separator between cool code and just code for me. Thank you for letting me know what decorator is and the usefulness of decorator.
If you want to add special functionality to certain functions. This would be particularly useful for multiple functions or if you’re developing a tool for others to use
Well… I made a tool once that for 3DSMax a couple years back. Some functions required a modifier to be added to a mesh, some didn’t. I used a decorator on those functions to then throw an assert, notifying the user that the modifier needed to be added to the mesh. This allows you to check for requirements on certain functions without actually including the checking code in the function itself. Allowing me to reuse the check code for multiple functions instead… Arguably, you can create checking functions that can be called in other functions that perform the same task. Allowing the same reuse of code. However, I like using it because at a glance, I can see what requirements a function has based on it’s decorators.
It's called a decorator because what it basically does is the decorator design pattern. You can use this to time a function call, or, a very good use case for this is also memoization/caching. Any decorator pattern will very likely make use of this
It sounds like any time you need a wrapper function spanning multiple functions. The video mentions measuring the function time for example. You could create a measuring function as a decorator and apply that to any function whose time you want to measure. I'm also just learning about this, but I think in most of these cases I would have just refactored an extra argument to the functions to pass in an object (variable or class) with the wrapper method or the results of the wrapper method, depending on what it needed. I can see the decorator simplifying refactoring, because you can just create a standalone function somewhere and then add @ everywhere, rather than interfering with the definition of the functions, but on the other hand, that seems like a recipe for long-term headaches in code maintenance. If there are different decorators littering the code, your brain has to go a lot further to tie the logic of it all together.
Judging by the comments, this syntax seems like wizardry to many people. Decorator syntax (@decorator) simply takes the function you are decorating and returns a wrapped function with the same name: def cache(f): results = dict() def wrapper(n): key_missing = 'cache key not found' if (r := results.get(n, key_missing)) == key_missing: results[n] = f(n) else: print(f'using cached result {{{n}: {r}}}') return results[n] return wrapper # @cache # def plus1(n): # return n+1 def plus1(n): return n+1 plus1 = cache(plus1) print(plus1(2)) print(plus1(1)) print(plus1(0)) print(plus1(2)) # Output: # 3 # 2 # 1 # using cached result {2: 3} # 3 That's the power of decorators. You can see a more generalized variant of this caching/memoizing idea in functools.cache and even one that only keeps a limited number of values in functools.lru_cache.
a great video as always, i have a suggestion that would probably take long normal videos, or multiple #short videos, but it would be appreciated by beginners like me... so long story short i wanted to make a snake game with pygame, but all tutorials contained "classes" and stuff related to classes, but i have never understood classes, as i found them very confusing plus not really useful in any way, as i have made multiple projects not really needing to use classes, and i didn't really want to just copy/paste the code from the tutorial, i wanted to actually understand what i was doing, what im saying is we would be very thankful if you could do tutorials explaining classes, what they are, how to use them, and most importantly why to use them, in a simple way for us beginners to comprehend, we'll be so grateful if you could fulfill my request, and from the bottom of my heart i thank you for all the effort you put into your content, keep up the great work (if you could, reply to my comment telling me if you would make or not to make the videos i've suggested)
Thank you for the sincere comments! Yes, I will absolutely be making videos on classes, it’s been on the agenda for a while now, just haven’t found the time yet, but it’s coming soon!
I like your vids but bro how do you "auto fill" the code? did u do it backwards and press ctrl z all the time? how else do you autofill the code in the exact right spots etc?
ChatGPT was suggesting to use decorators in my code and I've never heard of it at that point! So my answer was like I know christmas is around the corner but stop hallucinating about decorating my code😂😂
new to programming. Know the basics... Made a discord bot in python and had to use some "decorators" for the first time. Didn't know what they were called until know or how they worked.
the "wrapper" function could have been called anything you want. It doesn't have to be call wrapper. as long as it is return at the end it's all good. When he call "do_this()" it is as if he try to execute the function that is return by "my_decorator" . So yeah, the decorator allow you to add some additional logic to a function call. it's wrap itself around your function if your will
So calling the functions below wont do anything? It will only run the decorator? Or even we put @my_decorator it is still necessary to call those two functions?
Yes, it’s still necessary to call the function. When the function is called, it checks if it has a decorator on top before executing, if it does, Python passes the called function into the my_decorator function, and essentially gets replaced by the wrapper function which has extra functionality “wrapped” around the original function
But as a java developer i dont see the use of it, You still have to call the functions themself then why decorator? there must must be more info to this that you have not explain.
🥺💬 I think it is utility to help interface programmer to access of target function with a sequence logics. 📺💬📺💬📺💬 Give me some examples ... 🧸💬 You cannot have AgentID with callID and you cannot register because they return AgentID. 📺💬 Do you mean you cannot create conference call from existing callID ? 📺💬 Next time do not forget wrote the function 🐑💬 ➰ Hmmmmm.... *** Do not miss understand me, I am not looking from someone mistake and I use it in creative way ***
It’s essentially the modified version of the function you pass in. For example, do_this gets passed into my_decorator, and the wrapper function is returned to take it’s place
Bro, I swear I can't watch a python tip video without remembering that pythonistrash guy from instagram. Now everytime I watch any other python short or reel I keep thinking of "BIM BIM BAM BAM" 😰