Python Decorators in 1 Minute!

Поділитися
Вставка
  • Опубліковано 10 лют 2023
  • ⭐ Join my Patreon: / b001io
    💬 Discord: / discord
    🐦 Follow me on Twitter: / b001io
    🔗 More links: linktr.ee/b001io
    Background Music:
    Rain, Book And Cup Of Tea by | e s c p | escp-music.bandcamp.com
    Music promoted by www.free-stock-music.com
    Creative Commons / Attribution 4.0 International (CC BY 4.0)
    creativecommons.org/licenses/...
  • Наука та технологія

КОМЕНТАРІ • 320

  • @AbhishekBM
    @AbhishekBM Рік тому +452

    I can't believe decorators were this simple. After watching a lot of full length videos on decorators, this is the one that finally clicked. Nice job mate 👍

    • @googm
      @googm Рік тому

      you could've typed what is a python decorator into chatgpt and it would've given this exact example.

    • @oragnerby
      @oragnerby Рік тому +2

      Same here!

    • @clover6480
      @clover6480 3 місяці тому

      actually there is more to them. Normal decorators have three levels instead of just two

    • @azibekk
      @azibekk 3 місяці тому

      ​@@clover6480yeah but the main idea is that a decorator receives the function under it and returns a new function. 3 levels thing you are talking is a function that returns decorator when it is called. Then python uses that returned decorator as usual.

  • @jojojux
    @jojojux Рік тому +1292

    Very good explanation, I wish I had it back when I googled "What is that @ in python before a function def" and found a 3 pages explanation on site 2 in the results.

    • @retzerR
      @retzerR Рік тому +13

      I had the exact same experience (well I gave up after a while)

    • @poiuytrewq1553
      @poiuytrewq1553 Рік тому +13

      Chatgpt ftw

    • @retzerR
      @retzerR Рік тому

      @@poiuytrewq1553 There once was a dark time, no COVID and no ChatGPT.
      In all seriousness ChatGPT hasn't been here forever, and many beginners struggled to find information if they don't know what to search for. I personally struggled, and would have loved to have ChatGPT around.

    • @king_james_official
      @king_james_official Рік тому

      thankfully we have chatgpt now

    • @iunstable0
      @iunstable0 Рік тому +8

      never showed the results for me because google always dropped special symbols in the search query which i find pretty annoying

  • @NealeSamways
    @NealeSamways 10 місяців тому +74

    If only there were more videos like this on YT. Straight to the point, and ONLY the point. Very well explained in such a concise way. Thanks!

  • @mind_of_a_darkhorse
    @mind_of_a_darkhorse Рік тому +234

    Great short but very helpful video! I am new to python and was unaware of this ability!

    • @manojramesh4598
      @manojramesh4598 Рік тому +5

      I'm happy to see you are aware now

    • @Words-of-encouragement.-.
      @Words-of-encouragement.-. Рік тому +1

      Same my friend. There is always more to learn and it’s nice to stumble across these videos every now and again.

  • @vdantr3635
    @vdantr3635 Рік тому +87

    WTF man, I've been struggling for a good while with the topic listening to various explanations from different people and you made it clear in a minute?! Thank you so much and keep up the good work!

    • @liam_iam
      @liam_iam Рік тому +6

      "Python sees this @ symbol and understands that this function under it needs to be passed into a function called tictoc."

  • @cumulus3341
    @cumulus3341 Рік тому +6

    This is the kind of explanation i need.
    Short and compact, gets the points through.

  • @bdanon
    @bdanon Рік тому +11

    I finally found someone who explained it in practice. I watched a 2-hour lesson on functions, decorators and decorators didn't make any sense to me at the end of watching it. But your 1 minute video put it all together for me and now I understand, thank you very much

  • @MasterNickChannel
    @MasterNickChannel Рік тому +27

    If someone can explain something difficult in simple words - he masters that knowledge. That’s about this guy for sure

  • @first_m3m3
    @first_m3m3 Рік тому +8

    this is the best explanation on decorators I have ever seen. All other videos repeat the same formula, almost like making a cake, but they always confused me by using overly complicated terms...

  • @rezydev
    @rezydev Рік тому +42

    this channel is saviour to may of us new python coders. The thing which was difficult for me to understand in a video of 20 minutes he taught it in a simple way in less than 60 seconds.
    You'll grow and you'll help us learn too. Thanks buddy

  • @loewe_111
    @loewe_111 Рік тому +13

    Thanks for doing my idea, now i understand what it does. Great video as always!

  • @adityaalmighty1
    @adityaalmighty1 12 днів тому

    This was nice! Well done

  • @navyberries
    @navyberries 6 місяців тому +1

    love the brevity of your channel!

  • @arielmolina6277
    @arielmolina6277 4 місяці тому +1

    What an awesome video! Simple explanation and in 1 minute!!! Congrats!

  • @pav8369
    @pav8369 Рік тому +1

    Best explanation of decorators in Python I've ever heard.

  • @fr9714
    @fr9714 4 місяці тому

    Short, concise, to the point and exactly what I needed.

  • @cadematheson3109
    @cadematheson3109 Рік тому

    BRO! I've watched like 30 minutes of videos about decorators and was 100% lost. You just made it perfectly clear in 1 minute. NOICE!!!

  • @Szczurek15
    @Szczurek15 Рік тому +1

    You did something simple and IMHO pretty intuitive, yet somehow so much tutorials lacks this. You've explained the case on a real live example. People would left and right explain all of that by saying that it allows to pass methods "b" and "c" into method "a" automatically, what is somewhat true, but is as easy to understand as teaching driving by explaining laws of physics that cars obey. So kudos for the great explanation.

  • @C22_
    @C22_ Рік тому +8

    I would love some one-on-one training. Whatever I need to do to be as sharp as you. These videos are great.

  • @skf957
    @skf957 5 місяців тому

    Like others in the comments section I've watched other, much longer, videos on the subject and was still left confused. In ONE minute you have provided the most simple explanation! Thank you.

  • @muralidhar40
    @muralidhar40 5 місяців тому

    You killed it, brother!
    Can u make a 1 min short on decorators with parameters

  • @little_tornado1804
    @little_tornado1804 Рік тому

    I’ve seen this in other languages but no one explaining it ever used the key term “Decorators”. Thank you for making me aware of this!

  • @RaglansElectricBaboon
    @RaglansElectricBaboon 2 місяці тому

    Lots of nice tricks for this learner in one short video. Thanks.

  • @danielvega646
    @danielvega646 9 місяців тому +2

    We use a closure function that's gonna have access to the main function which is gonna send our decorated function as parameter and inside the closure it will be decorated. A decorator is easier to understand as a wrapper that receives our function as parameter to be used inside another function.

  • @ngonidzashechizororo
    @ngonidzashechizororo 8 місяців тому

    I'm following you for your simplicity and profound understanding. You just helped a brother.

  • @awaisahmad5908
    @awaisahmad5908 6 днів тому

    wow it's a very great explanation
    I was so confused about decorators earlier on.

  • @xXhotshot55Xx
    @xXhotshot55Xx 6 місяців тому

    This is probably the clearest explanation on decorators I've ever seen.

  • @tomasgodoy9625
    @tomasgodoy9625 Рік тому +3

    Your explanations are amazing!

  • @lorddug1892
    @lorddug1892 2 місяці тому

    Dont usually comment on videos but this was really helpful! Good job

  • @user-gz2nl9hl8l
    @user-gz2nl9hl8l 7 місяців тому +1

    Literally the best explanation on the internet!

  • @Gabriel-no6wv
    @Gabriel-no6wv Рік тому

    God, I love this kind of tutorial, quickly and very understable...

  • @znefas
    @znefas Рік тому +20

    to be a little more specific, decorators, afaik, simply take your function and replace it with whatever function is returned by your decorator, in this case the wrapper function
    this makes use of closures, which means that functions keep whatever data they've been given access to when returned, even if the scope they were defined in is gone
    this means you can also pass other stuff to decorators, and that can be very useful to create stuff like unit tests

    • @davidgood840
      @davidgood840 6 місяців тому +2

      This was helpful as I wasn't sure why the wrapper function was necessary .

  • @gumse666
    @gumse666 7 місяців тому

    Great video. I watched 4 other long videos about this without fully understanding. After your 1 minute video it's all clear to me. It's a lot like the time function in Bash.

  • @sumdude132
    @sumdude132 Рік тому +5

    I actually learned alot from this video.

  • @DayReverse
    @DayReverse Рік тому +3

    If only I knew this a week ago, it'll make my assignment way easier

  • @megsman4749
    @megsman4749 6 місяців тому

    Straight to the point. Fantastic.

  • @Fghhhg8883
    @Fghhhg8883 Рік тому +7

    Very quick but very good lesson, thanks!

  • @Aragon947
    @Aragon947 Місяць тому

    bro that is dope

  • @connorkapooh2002
    @connorkapooh2002 Рік тому +12

    Very nice and straight to the point :) definitely keep this up, there is a shortage of intermediate+ videos on Python

    • @2raddude
      @2raddude Рік тому

      Look up the channel mCoding, he’s fantastic

    • @jh_esports
      @jh_esports 5 місяців тому

      the compsci class in my physics major calls this "introductory", now I'm scared of what's to come

  • @akaTelo
    @akaTelo Рік тому

    This was a short but informative way to explain this concept. Very helpful, thanks

  • @thepackbot
    @thepackbot 8 місяців тому

    THAT. WAS. AWESOME!

  • @shikaiji2574
    @shikaiji2574 24 дні тому

    short, precise, perfect

  • @lumino8852
    @lumino8852 Рік тому

    literally the most effective way to explain decorators

  • @alarii2582
    @alarii2582 Рік тому

    Finally a good python tutorial. Most short tutorials on UA-cam are just: "Want to solve this problem? Just use this library and it'll do it for you"

  • @KenLaw-fu7wh
    @KenLaw-fu7wh 5 місяців тому

    Thanks for saving me in coding interview,Nice video!

  • @brunomendes4159
    @brunomendes4159 2 місяці тому

    THANKS!!!! YOU ARE AMAZING!!!

  • @bubblebath2892
    @bubblebath2892 2 місяці тому

    woah ...1 min and you nailed it

  • @itsaj2698
    @itsaj2698 4 місяці тому

    Absolutely amazing content bro! A complete python tutorial for beginners would be priceless, pls try to make one 🙏

  • @etekweb
    @etekweb Рік тому

    Neat! I used this recently for a SocketIO Python project but didn't really understand how it worked behind the scenes.

  • @francisrayquintana5119
    @francisrayquintana5119 4 місяці тому

    I'd like to pile on the praises here to boost your channel. Back when I was learning Python, wrappers were one of the things that I was having difficulties understanding. That, and *args and **kwargs. Both of which I understood clearly in your videos. Keep up the good work, and hoping success for your channel.

  • @oosmanbeekawoo
    @oosmanbeekawoo Рік тому

    Wow! I never thought I would understand!

  • @solidkundi
    @solidkundi Місяць тому

    amazing explanation!

  • @Rubbernecker
    @Rubbernecker Рік тому

    Dammit, this is great! Gonna use this at work tomorrow!

  • @mateusvitorino
    @mateusvitorino Рік тому +1

    NICE AND SIMPLE! LOVE PYTHON!!!!

  • @kevinwoodrobotics
    @kevinwoodrobotics Рік тому

    That’s pretty amazing!!

  • @BT-te9vx
    @BT-te9vx Рік тому

    a crisp explanation with a good example of how a decorator function functions (pun intended)

  • @rkdeshdeepak4131
    @rkdeshdeepak4131 Рік тому +27

    One thing I am always confused about decorators is to use () or not while @func, also why define a wrapper and then return it, couldn't just execute those statementa directly in the decorator function

    • @samueljehanno
      @samueljehanno Рік тому

      ikr

    • @not_vinkami
      @not_vinkami Рік тому +1

      Words simply can't explain that.
      I tried to type it out here, but I deleted all my writings after I wanted to talk about parameter handling and the use cases of it together with classes

    • @sufianhaq
      @sufianhaq Рік тому

      To answer your second qs.
      If wrapper() is called, then the function is execited and the decorator function returns a None Object which is not callable. This means that any function the decorator wraps will become non callable.
      Hope this makes some sense.

    • @AetherBreaker1
      @AetherBreaker1 Рік тому +7

      To better answer your question, the reason why is because you need the decorator function (tictoc in this instance) to return a FUNCTION. The decorators job is not to execute the function, but to place more code around another function, to be executed later, thus by returning a function, you have something you can call later.
      if you were to do away with the wrapper function, in the current example of the video, there would be nothing to return, which would lead to the explanation that Sufian Haq provided

    • @eeriemyxi
      @eeriemyxi Рік тому +3

      Here's an easy way to understand this:
      i) @example
      ii) @example(foo="bar")
      iii) @example()
      in (i), because the function is not being called, '@' just takes `example` function to pass the decorated callable object to. Similar observation can be accepted normally too:
      ```
      >>> def func(): ...
      ...
      >>> func
      >>> print(func)
      ```
      in (ii) and (iii), because the function is called, '@' will wait until `example` returns something and take that value to pass the decorated callable object to.
      To conclude, `@`: `` should be a callable that accepts the decorated callable object as its first positional argument, this callable's result will be replaced as the new definition of the decorated function.
      ```
      import time
      def dec(x):
      t1 = time.time()
      x()
      print(time.time() - t1)
      @dec
      def func():
      time.sleep(2)
      # results are shown at runtime without having to call `func`.
      ```
      ```
      class Foo:
      def __init__(self, text: str):
      print(text)
      def dec(func):
      return Foo
      @dec
      def func():
      ...
      func("hello world")
      ```
      ```
      class Foo:
      def print_text(self, text: str):
      print(text)
      def dec(*, text):
      def wrapper(func):
      print(text)
      return Foo
      return wrapper
      @dec(text="hello world")
      def func():
      ...
      func().print_text("bye world")
      ```
      These are working examples. A decorator is simply a function and is expected to return something callable to pass the function object being decorated. Python gave it a unique syntax because they can and because the syntax makes sense. Decorators can also accept arguments because it's just a function as I said.

  • @victorbrylew1775
    @victorbrylew1775 11 місяців тому

    Important part of decorators is ability to use initial function without any changes side by side with our new decorated version. So you need to import wraps from functools and to use it in your logic.

  • @LurkerPatrol5
    @LurkerPatrol5 9 місяців тому

    What the actual heck bro. I have been learning python since 2015 or so and never understood decorators no matter how much it was taught. You did in 1 minute what 8 years couldn't. Thank you!

  • @mcpr5971
    @mcpr5971 4 місяці тому

    That explanation was faster than the pop-up window timeout asking for my email when I use the SEO'd top google results.

  • @adityaghai220
    @adityaghai220 2 місяці тому

    just brilliant

  • @rezazeraat1890
    @rezazeraat1890 2 дні тому

    Good interview I learned a lot

  • @managMent_
    @managMent_ Рік тому +1

    I was bashing on Python quite a lot recently, but damn this is actually a really really good functionality!

  • @christianremboldt1557
    @christianremboldt1557 Рік тому

    This was indeed very helpful!

  • @vivanillah07
    @vivanillah07 Рік тому

    I wasn't expecting to learn new things about python today, but I'll take it

  • @ChandravijayAgrawal
    @ChandravijayAgrawal 3 місяці тому +1

    I never realised decorators were just fancy way to call normal functions, I have seen so many of them but was never able to remember the syntax until now

  • @liquathrushbane2003
    @liquathrushbane2003 Рік тому

    That is a legendary explanation.

  • @theo1103
    @theo1103 4 місяці тому

    sooo good

  • @davidcahan
    @davidcahan Місяць тому

    This example finally drove it home for me

  • @Robert-qw3lr
    @Robert-qw3lr 4 місяці тому

    I had no idea this existed. I'm doing this asap

  • @AliHamza-en8cn
    @AliHamza-en8cn Рік тому +2

    Incredible helpful I didn't know that thanks

  • @Abossow77
    @Abossow77 Рік тому +13

    Hey! This really helped! But What is the purpose of the wrapper? Can it be done without it?

    • @YoSoyWerlix
      @YoSoyWerlix 4 місяці тому

      Same doubt, did you get it lateral?

  • @toolbelt
    @toolbelt Рік тому

    Thanks for this. Most helpful and well explained.

  • @laponiec
    @laponiec 8 місяців тому

    The only intelligent explanation of decorators! Thank you very much!

  • @sadhlife
    @sadhlife Рік тому

    small tip, that \ at the end of the first string in print is not needed. inside parentheses, strings on multiple lines are concatenated with no joiner between them.

  • @grayscodinglab
    @grayscodinglab Рік тому

    Your videos are so awesome!

  • @iwinwinwinwinwin
    @iwinwinwinwinwin Рік тому

    Already knew this. Liked for other patterns

  • @adamp185
    @adamp185 Рік тому

    Finally somebody explained it right! THANK YOU!

  • @foreverunsure
    @foreverunsure Рік тому

    man i love your videos

  • @JDoucette
    @JDoucette 6 місяців тому

    Great explanation. Thanks. Nit pick: in this fantastic example, time.time can be replaced with perf counter for precision.

  • @adilsaju
    @adilsaju Місяць тому

    so good

  • @miroslavbabenko1953
    @miroslavbabenko1953 11 місяців тому

    Just amazing, thank you ever so much!

  • @SpesMagisteriiGradus
    @SpesMagisteriiGradus 3 місяці тому

    WOAH thank you

  • @LazyCat-bq7sz
    @LazyCat-bq7sz 7 місяців тому

    Yes, now i understand. Thank you.

  • @CallmeDou
    @CallmeDou 4 місяці тому

    jesus christ i understood it in no time, been doing the angela python course 4 fcking videos and i cant , get lost in all the functions she keeps naming function....... thank smy guy you are god sent

  • @ulfen69
    @ulfen69 6 місяців тому

    The beast of explanation.
    This example can hardly be improved.

  • @srb9767
    @srb9767 Рік тому

    Great Video, thanks for the info

  • @thefanboy3285
    @thefanboy3285 5 місяців тому

    Suupa video. Helped me understand decorators in general ! Though, I have to ask. Does the same logic applies to JS future ? (Currently Typescript) ?

  • @KelvinKamHK
    @KelvinKamHK Рік тому

    This channel is awesome :D

  • @moviemusicvideochannel7102
    @moviemusicvideochannel7102 Рік тому

    Dude I love you.

  • @SusanAmberBruce
    @SusanAmberBruce Рік тому

    Beautiful

  • @bettercalldelta
    @bettercalldelta Рік тому +5

    Basically:
    @deco
    def func():
    ....
    is the same as
    func = deco(func)

    • @farpurple
      @farpurple Рік тому

      Ohoh..
      it sounds slightly similar to lambda, maybe, should think about that

    • @hoangecg
      @hoangecg Рік тому

      😮 thanks u guy somuch. Now i got it

  • @kennethbeal
    @kennethbeal 5 місяців тому

    Wow, how simple! Decorators are just wrappers. The wrapping around a box is sometimes decorative. :)

  • @user-dj8ws1mc6f
    @user-dj8ws1mc6f 8 місяців тому

    Amazing explanation!

  • @sulaimanfawwazabdillahkari6735
    @sulaimanfawwazabdillahkari6735 4 місяці тому

    What theme do you use for your VS Code? It looks kinda cool and clean

  • @Apis035
    @Apis035 Рік тому

    What font and theme do you use? That looks fancy

  • @elhipster1
    @elhipster1 10 місяців тому

    fantastic explaination! Thank you for making this I now completely understand. After staying to myself, 3 minutes ago, "hey what is that @ symbol? It seems important."

  • @enderarchery2153
    @enderarchery2153 Рік тому

    omg! I was always wondering what they did

  • @setharnold9764
    @setharnold9764 Рік тому

    Good stuff

  • @cristianionascu
    @cristianionascu 6 місяців тому

    Excellent