Python Decorators Made Easy

Поделиться
HTML-код
  • Опубликовано: 30 апр 2018
  • In this video we'll be learning about a cool feature in Python called decorators, we'll be learning how to use them and what they're for.
    Go to howcode.org for more!
    Link to DigitalOcean: howco.de/d_ocean
    Link to howCode Facebook: howco.de/fb
    Link to howCode Twitter: howco.de/twitter
    Link to /r/howCode: howco.de/reddit
    Don't forget to subscribe for more!

Комментарии • 159

  • @magneat
    @magneat 3 года назад +4

    Correct code that works properly:
    def check(func):
    def inside(a, b):
    if b == 0:
    print("Can't divide by Zero")
    else: return func(a, b)
    return inside
    @check
    def div(a, b):
    return a / b

  • @JoaoBR85
    @JoaoBR85 4 года назад +94

    You forgot to "decorate" your line 7 with a return, before func(a, b). Good stuff anyway, thanks.

    • @migueljr6147
      @migueljr6147 4 года назад +1

      Obrigado, não estava achando o motivo que ele imprimia None kkk

    • @nikhilthakkar9087
      @nikhilthakkar9087 3 года назад +1

      Nice one.. that was giving me errors not anymore ..

  • @DanielTrivino-qn3br
    @DanielTrivino-qn3br Год назад +12

    Great explanation! I believe it is missing 'return' before func(a,b) in the decorator:
    def check(func):
    def inside(a,b):
    if b == 0:
    print("Can't divide by 0")
    return
    return func(a,b)
    return inside

    • @Ayanwesha
      @Ayanwesha 10 месяцев назад

      Yes otherwise it will show 'None' value

  • @JasonGabler
    @JasonGabler Год назад +2

    Why is this better than a plain, straightforward call to the original function inside a new function without all the abstraction of decorating? This video is great at explaining the mechanics, but even one sentence as to why they are superior would be great.

    • @xXhotshot55Xx
      @xXhotshot55Xx Год назад +1

      This is what I'm searching for too. I understand how it works, but I don't understand why it's any better than writing a proper function that handles it's own checks in the first place.

  • @hoola_amigos
    @hoola_amigos 6 лет назад +41

    These videos are gold for beginners like me.. short, concise and most importantly precise and to the point!
    Please keep these coming.!!

  • @vijaynrao2499
    @vijaynrao2499 Год назад +1

    You know the concept of decorators genuinely and you have explained it so beautifully. Thank you Francis!

  • @bsmaheshkumar5328
    @bsmaheshkumar5328 3 года назад +16

    What an amazing explanation, I have watched a lot of other YT videos to understand Decorators. But This one completely helped me to understand about the decorators that too within 4 Mins.

  • @kannanraja9711
    @kannanraja9711 4 года назад +9

    After trying to understand Decorators in many site, I finally turned to YT, and there it goes!! within 3 minutes understood why and what Decorators are! Good Explanation indeed!!!

  • @Jun-qj4mz
    @Jun-qj4mz 4 года назад +1

    It's so clear to understand, the easiest and clearest explanation

  • @THOTHO-ie5lz
    @THOTHO-ie5lz 3 года назад +1

    Does decorator always require a nested function?

  • @MayurPatil
    @MayurPatil 6 лет назад +23

    Dude you saved my next seven days to understand and make decorators work.

  • @blenderremastered9959
    @blenderremastered9959 4 года назад +5

    wow this is the most concise short explanation from someone finding other explanations too hard to understand on decorator, in life people don't learn thing because some people are bad in explaining. big thank to you

  • @RameenFallschirmjager
    @RameenFallschirmjager 4 года назад

    Finally someone could reach me to teach me decorators! You earned a subscriber sir!

  • @trivikram1988
    @trivikram1988 5 лет назад

    Awesome and thanks for the clarity u feed me on decorators

  • @Alphabetbubi
    @Alphabetbubi 5 лет назад

    How does the check function get the a and b parameters though???

  • @davidpham6330
    @davidpham6330 4 года назад +4

    In what scenario would you do this instead of actually going inside and adding logic to the original function? Wouldn't that be easier, faster and less confusing than creating a decorator?

    • @zacharypeterson4178
      @zacharypeterson4178 4 года назад +5

      If you have to add the check to multiple functions, or you only want to temporarily modify the function, this is useful

    • @samiam.402
      @samiam.402 2 года назад

      I'm still trying to figure this out myself. (And since you ask this a year ago, you probably are good to go by now lol) But I know they can be useful when building a webapp, using something such as Flask. Inside your main Python file, you will have functions that will execute when some visit a page, and as you build it out, using decorators defining different routes can help you add multiple endpoints/routes to the same function.

    • @TheStickofWar
      @TheStickofWar 2 года назад

      ​@@samiam.402 @David Pham
      One such scenario is when you wish to wrap behaviour around a function, such as a logger.
      Another such case is when you want to take third party code (code you cannot change, like a library) and add functionality to it. You can simply wrap their functions with your decorators to get custom behaviour.
      Finally, to combat the "actually going inside and adding logic to the original function", you can think of this in terms of functional programming perhaps. But you can use decorators to compose new functions, where they may share the same core functionality but you may not want to write the new functions in source code (perhaps there are many permutations), and instead build them dynamically.

  • @victornnah3920
    @victornnah3920 5 лет назад

    What theme are you using?

  • @elsholz2365
    @elsholz2365 6 лет назад +3

    I didn't even know it is possible to create nested functions in Python ^_^
    That's good to know

  • @jastriarahmat659
    @jastriarahmat659 5 лет назад

    is this something like callback in JS?

  • @dasgoll
    @dasgoll 6 лет назад

    Thanks. Best explanation ever!!!

  • @baphnie
    @baphnie 4 года назад

    This is only useful when you don't have access to the original function, correct? Or, can you now use either version of the function, and if so, how would you call the original form?

  • @Cytzix
    @Cytzix 5 лет назад +21

    That is an awesome explanation. Thank you!

  • @ReddSpark
    @ReddSpark Год назад

    Thanks this was super helpful. It also helped my learning to test and see that print(check(div)(10,0)) is valid syntax.

  • @reshaknarayan3944
    @reshaknarayan3944 4 года назад

    Awesome, clear and concise

  • @THOTHO-ie5lz
    @THOTHO-ie5lz 2 года назад

    won't func(a,b) get execute twice? Once for inside() definition and another time upon executing inside() via return?

  • @apderic1079
    @apderic1079 6 лет назад

    That was simple and easy , I understand it now thank you

  • @idenkritik
    @idenkritik 2 года назад +1

    It is the better explanation what I'v seen! Thank!

  • @atreushouse8848
    @atreushouse8848 10 месяцев назад

    Hello i accidentally stumbled on this video while looking looking for a wk to understand decorators since english is not my 1st language and you've explained it so well thank you

  • @acidjumps
    @acidjumps Год назад

    Thank you ! I was confused about the @ syntax.

  • @komalthecoolk
    @komalthecoolk 5 лет назад

    Straight to the point. Thanks!

  • @classicrockonly
    @classicrockonly 5 лет назад +11

    Apparently with Python 3.6.7 if I follow your code line for line the output is always "None", but once the decorator is removed it properly returns the divided value.
    EDIT: forgot to add - at line 7 if you add return then your code is correct

    • @magneat
      @magneat 3 года назад

      can you please provide normal code that works? Instead of this NONE explanation in video :-/

    • @classicrockonly
      @classicrockonly 3 года назад +3

      @@magneat Hope this helps...I don't know how RUclips will format this, so format accordingly :)
      #!/usr/bin/env python3
      def check(func):
      def inside(a, b):
      if b == 0:
      print("Can't divide by 0")
      return
      return func(a, b)
      return inside
      @check
      def div(a, b):
      return a / b
      print(div(10, 0))
      The major take away is that it is supposed to be "return func(a, b)", not "func(a, b)

    • @magneat
      @magneat 3 года назад

      classicrockonly yeah, thank you. Though I figured it out myself already. And didn’t you forget to put ELSE there?

    • @classicrockonly
      @classicrockonly 3 года назад

      @@magneat Nahh it's not necessary. If it's true it will return and ignore the rest of the inner function. So the else is implicit

    • @magneat
      @magneat 3 года назад

      classicrockonly btw, just today saw tutorial which said that putting single RETURN is “returning None implicitly”, which is considered a bad practice. And that Indian developers are doin this often in their code. “explicit is better than implicit” is named a better practice, like more correct way.

  • @dominiquefaulques5642
    @dominiquefaulques5642 Год назад

    Best explanation I've found so far. Thanks a lot 👍👏

  • @azmisudrajat
    @azmisudrajat 5 лет назад

    Wow, the explanation is easy to understand.

  • @th2315
    @th2315 2 года назад

    is this the same as function closure in javascript?

  • @donatellodonini3147
    @donatellodonini3147 3 года назад +1

    So, i have a question:
    The inner function is useful because in that you can write the parameters of the outer function's parameter, wich is a function

    • @drewsarkisian9375
      @drewsarkisian9375 10 месяцев назад

      That's not a question, that's a statement.

  • @William_Clinton_Muguai
    @William_Clinton_Muguai 3 года назад

    All I can say is-Thank you. I finally got it.❤️❤️❤️

  • @ArcaneMachine
    @ArcaneMachine 4 года назад +2

    Beautiful video: short, informative, and no BS filler.

  • @RameenFallschirmjager
    @RameenFallschirmjager 4 года назад

    the concept of decorators is very cool!

  • @dlz1893
    @dlz1893 4 года назад

    Awesome video. Very easy to understand.

  • @kochcj1
    @kochcj1 3 года назад +1

    The inside function should be returning the result of func(a,b), not just calling it. Without returning the result of that call, division by non-zero is just going to print out None.

  • @Piece101
    @Piece101 4 года назад +1

    If you return a/b in insider function , it will not through error for non zero values. by very nice explanation. really appreciated.

  • @jeevanjeenu5812
    @jeevanjeenu5812 3 года назад

    Thanks dude your video made me understand this concept with in 3 min :)

  • @shubhambiniwale9623
    @shubhambiniwale9623 5 лет назад +2

    after watching videos of20,20 mins, I got my concept completely clear in your 3mins video! Thank you! keep going on

  • @KrypticDonut
    @KrypticDonut Год назад

    Thank you for explaining this

  • @mmustap3
    @mmustap3 2 года назад

    Great explanation in common english, thanks!

  • @matheusft
    @matheusft 3 года назад

    Great simple video. Thanks for that!!!

  • @Riccardo4106
    @Riccardo4106 5 лет назад +2

    You explained it greatly and in 3 minutes. Great for a very quick and clear introduction! Compliments!

  • @gongjiaji2489
    @gongjiaji2489 5 лет назад

    thank you. I know basics now.

  • @js-bf6nh
    @js-bf6nh 5 лет назад

    nice neat and clean. thanks for the vid.

  • @adamainsworth2903
    @adamainsworth2903 Год назад

    How come these examples always do something like div = check(div) as in the video. Would it work if he just wrote def check(div) in the decorator itself rather than def check(func), or does it have to be an empty parameter to start with?

    • @Johnny-nq9bh
      @Johnny-nq9bh Год назад

      in 'def check(func)" func is just a local name, it could be anythong, if you call this div then in line 7 you would need to change code from func to div

  • @utsavjolapara4366
    @utsavjolapara4366 5 лет назад

    Proper good job mate.

  • @sc0820
    @sc0820 3 года назад

    very easy to understand . Decorator is just putting a function A before a function B in execution so that the whole execution is more desirable without editing function B. In other words, if you do not want to edit a function but you need another result from that function, just decorate it. Decorator is just a wrapper.

  • @malicant123
    @malicant123 5 лет назад

    Thank you for this.

  • @miguelbarroso_
    @miguelbarroso_ 3 года назад

    Very Good explanation. Thanks!

  • @SanataniAryavrat
    @SanataniAryavrat 4 года назад

    easily explained using this example... understood the basic and learned something new today.... can I have some more complex examples on decorators? or may be a small project that explains the usability of decorators in more advanced ways... thanks bro.

  • @Piece101
    @Piece101 4 года назад

    def check(func):
    def inside(a,b):
    if b == 0:
    print("Can't divide by Zero")
    else:
    return a/b
    return inside
    @check
    def div(a,b):
    return a/b
    print(div(10,2))

  • @crish2480
    @crish2480 2 года назад

    great tutorial!

  • @Abhi-ms8pk
    @Abhi-ms8pk 6 лет назад

    Thank you!

  • @VinBhaskara_
    @VinBhaskara_ 5 лет назад +1

    beautiful python

  • @Johncowk
    @Johncowk 3 года назад

    Very clear, thanks!

  • @luansouzasilva31
    @luansouzasilva31 4 года назад +2

    Examples in this cases are essentials, and your example was perfect. Thank you!

  • @arnodunstatter
    @arnodunstatter Год назад

    If you must have access to the original function's definition in order to use the @ operator to declare a decorator function to replace the original function with, and doing so immediately replaces the original function with it's extended, decorated version, then why not just simply extend the function definition right there at the definition which you necessarily have access to? I don't understand how this is useful. Please halp

  • @user-tl9rp2pm6r
    @user-tl9rp2pm6r 3 года назад

    when implementing your code, when i try to divide 10 by 5, it does not give me an output

  • @VikramKumar-bk8jl
    @VikramKumar-bk8jl 6 лет назад +4

    In line number 7, why we are calling func(a,b) that too in inside(a,b) function ?

    • @deadlock107
      @deadlock107 6 лет назад +8

      Line 7 should be "return func(a,b)", otherwise "inside" always returns "None".

  • @Study-Only-gb7gq
    @Study-Only-gb7gq 10 месяцев назад

    straight on point

  • @bluebird563
    @bluebird563 5 лет назад

    good explanation thanks

  • @Alexandra-he8ol
    @Alexandra-he8ol 3 года назад

    Cool explanation for beginners like me👍🏻

  • @denmak5881
    @denmak5881 6 лет назад

    Thank very simple explanation

  • @vinsmokearifka
    @vinsmokearifka 5 лет назад

    Good explaination.thanks

  • @tipster360
    @tipster360 Год назад

    Superb Video!

  • @Tyokok
    @Tyokok Год назад

    thanks for the video! but why it returns None, as it gets printed out? thank you!

    • @xXhotshot55Xx
      @xXhotshot55Xx Год назад

      "None" is the default value returned by python when nothing else gets returned.

  • @tech-n-data
    @tech-n-data Год назад +2

    Best explanation of decorators and you managed to do it under 4 minutes! Thank you.

  • @codewithkolhar3131
    @codewithkolhar3131 5 лет назад +1

    good work.

  • @plekkchand
    @plekkchand 2 года назад

    func is executed twice?

  • @kavichandmohan3407
    @kavichandmohan3407 5 лет назад

    nice explanation.. liked it

  • @K3vyB
    @K3vyB 5 лет назад +8

    so basically decorators are functions that get called when their underlying function gets called, with a default first argument being the decorated function.
    wtf

  • @BijouBakson
    @BijouBakson 10 месяцев назад

    Thank you

  • @okfine7550
    @okfine7550 3 года назад

    Thanks a lot broo

  • @saisubbu797
    @saisubbu797 6 лет назад

    crystal clear!

  • @StrangeIndeed
    @StrangeIndeed 3 года назад

    good stuff, thanks c:

  • @avisekssarma5592
    @avisekssarma5592 4 года назад

    good explanation

  • @user-ww2lc1yo9c
    @user-ww2lc1yo9c 3 года назад

    how come you don't have 10 million subscribers yet?

  • @alexyousefian4359
    @alexyousefian4359 4 года назад

    good example!

  • @omar_5352
    @omar_5352 4 года назад

    Could not understand the need for the insider function. Why can not it be just the checker function ?

  • @lynxcommando
    @lynxcommando 5 лет назад

    Simple is the best!

  • @jamu8060
    @jamu8060 6 лет назад

    Can I use this to run Hello World or any function whatsoever?

  • @fiftysix1957
    @fiftysix1957 4 года назад

    Good stuff

  • @aleksandravasileva2289
    @aleksandravasileva2289 Год назад

    thanks!

  • @thecoderguy_0001
    @thecoderguy_0001 Год назад

    great video, gem

  • @ShaanGola
    @ShaanGola 5 лет назад +1

    beautifully yet strong explanation of decorators...very useful...please post more videos on the key feature of Django/Python

  • @eliscrubs1483
    @eliscrubs1483 2 года назад

    thanks king

  • @Norogoth
    @Norogoth 2 года назад

    Nice onedark theme.

  • @XorAlex
    @XorAlex 4 года назад

    Awesome

  • @thecoderguy_0001
    @thecoderguy_0001 Год назад

    just one suggestion, if you try to explain with doing debugging alongside your videos will be superb.

  • @jalil_kartal
    @jalil_kartal 2 года назад

    thanks

  • @productionoutages
    @productionoutages Год назад

    best i've watched

  • @giokbilashvili32
    @giokbilashvili32 5 лет назад

    Write a function that takes the argument and transfers the factor of this number.
    Order the function decorator, which also gets the int argument and the result of the result, making the decoration - raises the argument and returns the result
    can i get a help? cant understand why my professor in university of computer science started teaching me from this shit...

  • @13Abhiram
    @13Abhiram 6 лет назад

    Neat!

  • @jesushernandez-gw2qj
    @jesushernandez-gw2qj Год назад

    Thanks I was struggling lol

  • @torreydale
    @torreydale 4 года назад +1

    @howcode I didn't see "Something else" added in your earlier example. I only saw you type in an empty string. Furthermore, this would have been easier to follow if you did this within an IDE instead of going back and forth between an editor and a command line interpreter.

    • @malandro2023
      @malandro2023 Год назад

      The concept is pretty clear (imo); I don't see much added value in persnickety requests; I mean, other visitors aren't complaninig at all, that makes me think that the guy accomplished his goal (sharing knowledge) and helped me with mine (understand the basics of how decorators work)... and probably, others' too.