Тёмный

What Are Python DECORATORS??  

b001
Подписаться 252 тыс.
Просмотров 608 тыс.
50% 1

⭐ Join the Byte Club to practice your Python skills! ($2.99/mo): / @b001
🐦 Follow me on Twitter: / b001io
Background Music:
you had me at hello by ikkun (ex. Barradeen) | / ikkunwastaken
Music promoted by www.free-stock-music.com
Creative Commons / Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0)
creativecommons.org/licenses/...

Опубликовано:

 

13 июн 2023

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 207   
@rodanban222
@rodanban222 Год назад
the most important thing is that decorators should cover possible arguments to function def wrapper(*args, **kwargs): func(*args, **kwargs)
@MelihGMC2
@MelihGMC2 3 месяца назад
649 likes and 0 replies? Let me fix that
@rodanban222
@rodanban222 3 месяца назад
@@MelihGMC2 you're the best :)
@willd0g
@willd0g 2 месяца назад
Definitely preferred the simplest case first - Previous examples have always tripped me up. Thanks for the comment now that ive got the basics
@30sachinsharma4
@30sachinsharma4 Месяц назад
Yup bro for arguments
@James-the-elder
@James-the-elder Год назад
This is the most straightforward explanation of Python decorators I've seen so far.
@TAP7a
@TAP7a Год назад
Absolutely. Having read dozens of articles, this 60s video is the only presentations I've seen that actually gets the message across
@bankaihampter2802
@bankaihampter2802 8 месяцев назад
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
@James-the-elder
@James-the-elder 8 месяцев назад
@@bankaihampter2802Yes but it's a 60 seconds video. If you understand the basics, you are more likely to read further
@charlescrawford9972
@charlescrawford9972 8 месяцев назад
I think I'm missing something fundamental here. When should a decorator be utilized?
@mozvi1436
@mozvi1436 7 месяцев назад
This is the best beginner explanation imo yep
@2Sor2Fig
@2Sor2Fig Месяц назад
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.
@SpaghettDev
@SpaghettDev Год назад
to make it more clear, a decorated function called f basically does this: f = my_decorator(f)
@ferrumignis
@ferrumignis Год назад
Why is the wrapper function within the decorater function needed?
@SpaghettDev
@SpaghettDev Год назад
@@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()
@charlescrawford9972
@charlescrawford9972 7 месяцев назад
@@SpaghettDev So it's for localization of functions? I've gone over a lot of tutorials but this is the most confusing concept to me so far.
@lordmahakaal
@lordmahakaal 2 месяца назад
​@@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
@span4ev
@span4ev 3 месяца назад
I just needed a simple example of how decorators work to get the function name for error logging. Thanks
@murphygreen8484
@murphygreen8484 Месяц назад
From functools import wraps
@MichaelProstka
@MichaelProstka 10 месяцев назад
Kudos! This made WAY more sense than the 30 min video i just watched 😂
@FundamSrijan
@FundamSrijan 4 месяца назад
Freaking true
@ugulbertosanchez7978
@ugulbertosanchez7978 11 месяцев назад
FINALLY UNDERSTOOD IT!!!! thank you 😃
@josiah_maddux
@josiah_maddux 7 месяцев назад
Solid work. I was just wondering about these, lol
@alisoltani5636
@alisoltani5636 2 месяца назад
I have learned something that i used to do manually Thanks
@pyromancerforhire
@pyromancerforhire 2 месяца назад
That's very functional for the imperativetiness of Python
@prakashhariharabalan621
@prakashhariharabalan621 6 месяцев назад
Function pointers from c/c++
@anthonymann7679
@anthonymann7679 Год назад
What's a real world example as to why you would do this as opposed to just calling the functions normally?
@infiniteplanes5775
@infiniteplanes5775 Год назад
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
@RQ321
@RQ321 Год назад
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.
@TheBomb420
@TheBomb420 Год назад
Discord bots. Every single one.
@goncaloazevedo9822
@goncaloazevedo9822 8 месяцев назад
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
@Blaisem
@Blaisem 7 месяцев назад
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.
@sunayraj
@sunayraj 10 месяцев назад
Man, one can easily drag this into 30 mins *demy class.. Thank you.
@venky1922
@venky1922 Год назад
Thanks bro big shout out❤❤.It was great..
@SomethingRandomChannel
@SomethingRandomChannel 6 месяцев назад
Dude thank you this is great thanks
@curiousmind4870
@curiousmind4870 3 месяца назад
Beautiful!
@angeloc700
@angeloc700 Месяц назад
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 😂
@bloxfruit_player788
@bloxfruit_player788 Год назад
Me after 3000000 tutorials of decorators abt how they work, this video👿:
@timesink1024
@timesink1024 6 месяцев назад
lmao same thing with pointers in C. so overhyped and over/underexplained when you finally get a good explanation you're like "really?"
@irfankhanpatan4415
@irfankhanpatan4415 15 дней назад
Well explained
@-SHEESH-YIKES-
@-SHEESH-YIKES- 6 месяцев назад
I hope 🤞 one day I’d be able to code 🧑‍💻 like you bro 😎
@AOLARTES
@AOLARTES Год назад
Ty!
@ObiwanNekody
@ObiwanNekody 9 месяцев назад
Awesome is what they are.
@Steadyrock100
@Steadyrock100 6 месяцев назад
I'm learning new coding things everyday! You got some info on dictionaries? That would help!! You got a subscriber!!!!!!!!!!
@angelsv
@angelsv 7 месяцев назад
Decorators? To me, sounds like a nice Christmas gift with a lot of fancy "decorators" lol
@octillionbees5516
@octillionbees5516 8 месяцев назад
This is actually a monad!! It’s super cool that python has explicit support for them!
@leesixtwooneone
@leesixtwooneone 4 месяца назад
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.
@JustaJabberwocky
@JustaJabberwocky Год назад
Thx man
@BiteSizeP0dcasts
@BiteSizeP0dcasts 7 месяцев назад
That just looks like functions but with extra steps
@RonenCruze-ci3vw
@RonenCruze-ci3vw 4 месяца назад
You don't see that as cleaner code?
@bigjamar
@bigjamar Год назад
excelente..muchas gracias!
@ElantraMan
@ElantraMan 7 месяцев назад
*laughs in closures*
@TaylorPeterson913
@TaylorPeterson913 Год назад
I needed to know this!
@AverageSensei
@AverageSensei 2 месяца назад
I know how to do print("Hello World!") can I join the club?
@xPlay5r
@xPlay5r 9 дней назад
Also ChatGPT: class MyClass: def __init__(self, arg1, arg2): self.arg1 = arg1 self.arg2 = arg2 def existing_function(self): # Logic of existing function result = self.arg1 + self.arg2 print(f"Result: {result}") return result def my_function(self, custom_class): # Using custom_class into my_function result = custom_class.existing_function() # Additional actions print("Additional actions") return result obj1 = MyClass(10, 20) output = obj1.my_function(obj1)
@SobTim-eu3xu
@SobTim-eu3xu Месяц назад
Tnx
@jorenmartijn
@jorenmartijn Месяц назад
Sounds a lot like a class with a constructor
@KaviBisarya
@KaviBisarya Год назад
You are amazing at this!
@harleyfioretti1484
@harleyfioretti1484 2 месяца назад
I thought he was gonna rap about python and was excited. Still good video😅
@frenches1995
@frenches1995 7 месяцев назад
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😂😂
@JM_Tushe
@JM_Tushe Год назад
Nice example, I know what it does, I don't know what it can be used to.
@user-ip1rx2vs6j
@user-ip1rx2vs6j 7 месяцев назад
Looks like a callback function in javascript to me.
@sweethomes674
@sweethomes674 Год назад
Excellent
@OoverHeaven
@OoverHeaven Месяц назад
What would be the typical use case of a decorator? Solely for logging?
@Luix
@Luix 7 месяцев назад
Brain explosion
@Spyxxer
@Spyxxer 7 месяцев назад
Looks redundant to me that innermost function especially just calling it direct looks cleaner but i feel there must be a reason for the wrapper
@user-rm5qy2im2i
@user-rm5qy2im2i 9 месяцев назад
Subscribed
@florind7056
@florind7056 6 месяцев назад
decorators are like HOC in react
@patrickbyers3723
@patrickbyers3723 Год назад
Great simple explanation!
@jesterthelegend926
@jesterthelegend926 Месяц назад
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.
@warido37
@warido37 Год назад
do this. do that.
@Olaf2745
@Olaf2745 Год назад
What is the difference between the decorater and the wrapper. Or rather what is the use of the wrapper, doesn’t the decorator do it’s job?
@BanAaron
@BanAaron Год назад
A decorater is a wrapper. They're the same thing.
@Ruchunteur
@Ruchunteur Год назад
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
@valeriodeluca3391
@valeriodeluca3391 7 месяцев назад
Thanks 🙂 Decorators can "decorate" only other functions or other python elements too?
@marino3034
@marino3034 4 месяца назад
Can you show the input output caches?
@plazmaplayz2499
@plazmaplayz2499 Год назад
why is the purpose of def wrapper (): func?
@j.r.r.tolkien8724
@j.r.r.tolkien8724 2 месяца назад
Like closures in JavaScript I suppose.
@theupsider
@theupsider 4 месяца назад
Funny how decorators are simply the implementation of the decorator pattern.
@NamChin846
@NamChin846 4 месяца назад
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?
@bassturtle4
@bassturtle4 Год назад
This is amazing, keep it up
@sudeepranganath5975
@sudeepranganath5975 5 месяцев назад
AOP in spring. Simple here.
@shami9773
@shami9773 4 месяца назад
I am very very new to python and was wondering how you skip to the next line without executing the function.
@Thekingslayer-ig5se
@Thekingslayer-ig5se Год назад
Great
@RoyalYoutube_PRO
@RoyalYoutube_PRO 3 месяца назад
What is the relevance of wrapper?
@SethRadius1
@SethRadius1 6 месяцев назад
Me right now on Day Zero (preemptively) the trying to learn Python and attempting to understand this video: @_@;;
@stat_life
@stat_life Год назад
I still didn't get it
@maxhamman
@maxhamman Год назад
yeah im not there yet :)
@wissemaljazairi
@wissemaljazairi Год назад
Is it possible to combine multiple decorators?
@raviachan3071
@raviachan3071 Год назад
What IDE and theme is this? Looks great
@forstuffwow7145
@forstuffwow7145 Год назад
read thetop part of video
@epsi
@epsi Год назад
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.
@aislancesar
@aislancesar Год назад
Print debugging just evolved...
@ojasbhalerao3448
@ojasbhalerao3448 15 дней назад
Is this similar to wrapAsync func in javascript?
@rodbrowning
@rodbrowning Год назад
What If the function has arguments?
@polycrystallinecandy
@polycrystallinecandy 6 месяцев назад
Poor man's monad
@TheRuancarlo
@TheRuancarlo 11 месяцев назад
LOL, can I create a decorator as a class method and use it inside another class?
@MonirulIslam-ud3px
@MonirulIslam-ud3px Месяц назад
Whats the font name and theme name?
@ohimdabiggestbird
@ohimdabiggestbird Год назад
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)
@b001
@b001 Год назад
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!
@maestrulgamer9695
@maestrulgamer9695 3 месяца назад
What kind of program would need this?
@aloobaloo68
@aloobaloo68 Год назад
what's the theme of your editor? i'm asking for the third time 😂
@piedepew
@piedepew Год назад
Who asked?😂 /S he be like
@soubhagyasadhukhan4531
@soubhagyasadhukhan4531 11 месяцев назад
VS code most probably
@lokeshkumar-dq7yl
@lokeshkumar-dq7yl 10 месяцев назад
Spyder
@SOme_rAnDOm_GuY908
@SOme_rAnDOm_GuY908 10 месяцев назад
shades of purple Edit: Them name :)
@kstelakis
@kstelakis 6 месяцев назад
could this be used to create monads?
@mistermister1541
@mistermister1541 6 месяцев назад
Python is about clever code over simple readable code.
@hoanghuynh4110
@hoanghuynh4110 9 месяцев назад
Callback?
@midvisexual6710
@midvisexual6710 6 месяцев назад
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" 😰
@DylanOkyere
@DylanOkyere 8 месяцев назад
So a decorator is basically a function for a function?
@adithyag
@adithyag 6 месяцев назад
what is the theme you use for ur visual studio code?
@unvein1863
@unvein1863 5 месяцев назад
this is pycharm and he's using retrowave
@olivers.7821
@olivers.7821 8 месяцев назад
How do all of these just instantly appear?
@LastSpark
@LastSpark Месяц назад
what is that color scheme
@Adinasa2
@Adinasa2 5 месяцев назад
Which theme
@aliakbarkazeminiya2758
@aliakbarkazeminiya2758 6 дней назад
what this is theme ?
@winter7885
@winter7885 7 месяцев назад
why dont we just do my_decorator(do_this): is there any diffeerence to it
@andreiinthedesktopworld1178
Software pls
@NikolajLepka
@NikolajLepka 6 месяцев назад
why not just write "return lambda: func()"?
@montry.
@montry. 3 месяца назад
So middleware?
@aryanmithbawkar4309
@aryanmithbawkar4309 2 месяца назад
What is this vs code theme
@aidanknox2430
@aidanknox2430 Год назад
i was gonna make fun of python but thats actually p cool
@UCKszbcV
@UCKszbcV Год назад
So...decorators are basically a function factory?
@theseasmaroulis5331
@theseasmaroulis5331 Год назад
not exactly, it is syntactic sugar for the decorator design pattern.
@kidaz
@kidaz 8 месяцев назад
Why do you have to define wrapper?
@goncaloazevedo9822
@goncaloazevedo9822 8 месяцев назад
Because in reality you are calling wrapper when you call your function
@bemschurger
@bemschurger Год назад
Lmfao i didnt understand a single bit
@gnorse373
@gnorse373 9 месяцев назад
its a function for functions
@_danfiz
@_danfiz Год назад
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?
@b001
@b001 Год назад
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
@Joso997
@Joso997 Год назад
​@@b001it sounds like a delegate when you do not want to use classes
@fernandocamarena5634
@fernandocamarena5634 7 месяцев назад
Hard to read I’ll get to this when I get to it
@raurok
@raurok Год назад
Why do you have to return the wrapper ?
@b001
@b001 Год назад
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
@mustafagamer7358
@mustafagamer7358 Год назад
​@@b001why don't u just execute the do_this function in decrator instead of the wrapper or just make return the fun()
@sergiuszkot8116
@sergiuszkot8116 11 месяцев назад
Nice, so now let's try to explain difference between decorator and proxy 😂
@hesamasadinezhad6210
@hesamasadinezhad6210 6 месяцев назад
whats your theme name?
@unvein1863
@unvein1863 5 месяцев назад
retrowave in pycharm
@TheNewton
@TheNewton Год назад
So why not just do my_decorator(do_this()) as an argument
Далее
*Args and **Kwargs in Python
3:49
Просмотров 255 тыс.
Python Decorators Made Easy
3:53
Просмотров 128 тыс.
Редакция. News: 125-я неделя
48:25
Просмотров 1,8 млн
Python Decorators in 1 Minute!
1:09
Просмотров 511 тыс.
Never Do this in Python
0:56
Просмотров 73
OOP in Python | Object Oriented Programming
1:45:19
Просмотров 1,7 млн