5 Useful Python Decorators (ft. Carberra)

2024 ж. 13 Мам.
78 155 Рет қаралды

Here are 5 useful decorators that can help make your code more convenient to use! And a big thanks @Carberra for joining in on this video; do check him out if you love Python!
Check out Carberra:
/ @carberra
Github repository:
github.com/federicoazzu/five_...
▶ Become job-ready with Python:
www.indently.io
▶ Follow me on Instagram:
/ indentlyreels
00:00 Learning Python made simple
00:05 Intro
00:32 @retry
02:42 Sponsor
02:52 @cache
05:50 @get_time
07:51 @deprecated
10:58 @on_exit
13:51 Amazing

Пікірлер
  • Congratulations on getting the sponsorship deal!

    @anamoyeee@anamoyeee2 ай бұрын
    • Thanks, they're very easy to work with! Absolutely recommend them :)

      @Indently@Indently2 ай бұрын
    • I’m actually dating them rn. Like right. Now.

      @DrDeuteron@DrDeuteronАй бұрын
    • I just can’t deal with type annotations on an add function. Is this not DEVOlution ? Next we’ll be calling it “addi”, with “addf”, “adds”, “addl”…..I can keep going…addc,

      @DrDeuteron@DrDeuteronАй бұрын
  • Very nice collab! The deprecated decorator was a very much necessary functionality, especially for libraries. Coming from a Java background, not having this decorator in the main Python language surprised me.

    @wrichik_basu@wrichik_basu2 ай бұрын
    • May I ask what you do mean by that? Because Java indeed has one. You could argue with me that the semantics are not the same but syntactically they are the same ^^.

      @sir_no_name1478@sir_no_name14785 күн бұрын
  • When it comes to retries, you may want to have a look at the Tenacity library. E.g. Tenacity allows for random wait times, exponential wait times or even only retrying for certain exception types.

    @SuperVirus1978@SuperVirus19782 ай бұрын
    • Also has a cool name!

      @Indently@Indently2 ай бұрын
    • yep, certain exception is great. Catching any excepting is just nasty

      @kezif@kezif2 ай бұрын
  • One of the best uses of the cache decorator is in recursive functions. Every recursive call get's cached, meaning if you call factorial(n) and then factorial(n+2), only 2 extra recursive calls will be made, for a total of n+2 calls. Any call to factorial(m) for m =< n will also be entirely cached.

    @AntonioZL@AntonioZL2 ай бұрын
    • Fibonacci is the go-to function for demonstrating the cache decorator.

      @urkerab@urkerab2 ай бұрын
    • What would be a good demo is some use cases that demonstrate the advantages of @cache vs @lru_cache versus each other. When to use each.

      @michaelhoffmann2891@michaelhoffmann2891Ай бұрын
    • If you input numbers like 1000 you get a RecursionError. Also isn't it

      @cycrothelargeplanet@cycrothelargeplanetАй бұрын
    • ​@@cycrothelargeplanetyou can change the limit with the sys module

      @Omena0@Omena0Ай бұрын
  • Tenacity’s retry decorator is really good and quite expressive. Atexit: use a context manager with a try/finally block to close that database for most applications. Atexit mainly applies to long running python programs that are run as a server or daemon.

    @IceArdor@IceArdor2 ай бұрын
  • Simply the best videos for people learning Python. You're a highly effective communicator who has a teaching spirit. Thank you for helping!

    @juancharlie777@juancharlie7772 ай бұрын
    • Thanks for the kind words :)

      @Indently@Indently2 ай бұрын
  • I've also written the retry and the timing decorators a few times for various projects, I wish it were standardized in a built-in module

    @auroragb@auroragb2 ай бұрын
  • Some code that might be useful to my project, a source that looks well worthy of a sub, and a literal belly laugh. Thanks for that mate.

    @pldvs@pldvs2 ай бұрын
  • Once I finish a project that I'm working on I'll watch a lot of your videos and try to apply some new learnings to my old python projects, really informative things you're pushing out

    @workingguy3166@workingguy316617 күн бұрын
  • These are excellent (as are ALL of your videos). Thank you! 😺

    @dcollett@dcollett2 ай бұрын
  • Super informative, thank you!

    @patrickbg110@patrickbg1102 ай бұрын
  • Love your videos man! Super helpful towards improving my coding practices

    @texloch1401@texloch140118 күн бұрын
  • Probably one of the coolest things I ever created that I unfortunately no longer have was a decorator that would turn a function into a tkinter form automatically.

    @chair547@chair5472 ай бұрын
    • In what way? Like it would create a form for inputting arguments, and displaying function results?

      @LF-Me@LF-Me26 күн бұрын
    • @@LF-Me yeah exactly

      @chair547@chair54726 күн бұрын
  • Very cool stuff, Thank You!

    @alexanderzikal7244@alexanderzikal72442 ай бұрын
  • I like to add a filter for exception types when writing a retry decorator. When fetching some stuff, it might fail due to connection issues or a rate limiting. Then it is fine to retry it. But if you parse or transform the result in the same function, it will fail always if something is different than expected, so usually no need to retry it. And, my favourite case, if you cause a KeyboardInterrupt at the same time, would it retry it as well?

    @Kommentierer@Kommentierer2 ай бұрын
  • this was reallly helpfull , i was struggling to write this to evevry function i use to measure time or apply retry functionalliy

    @mohamedahmed4461@mohamedahmed446125 күн бұрын
  • atexit: Doug Hellmann's book about the Python 3 standard library pages 995-997 mentions three conditions when atexit will not be invoked: 1) the program dies because of a signal, 2) os._exit() is invoked directly, and 3) a fatal error is detected in the interpreter.

    @finnthirud@finnthirud2 ай бұрын
  • I like the sponsor!😂

    @Sailesh_Bhoite@Sailesh_Bhoite2 ай бұрын
  • A fun follow up video would be a brief overview on how to create your own decorators! I've done so, for some client specific code and it's a fun exercise 😁

    @michaelhoffmann2891@michaelhoffmann2891Ай бұрын
  • Excelent content, thanks for sharing it (: For those thinking about counting vowels in a str, the version below has time complexity of O(n) ```python def count_vowels(input_str: str) -> int: vowels = 'aeiouAEIOU' return sum(1 for char in input_str if char in vowels) ```

    @brunocunha9043@brunocunha90432 ай бұрын
  • It's appreciable ❤

    @dipeshsamrawat7957@dipeshsamrawat79572 ай бұрын
  • You can also use lru_cache instead of cache, it will automatically remove the cache which is not used recently.

    @samrat00725100@samrat007251002 ай бұрын
  • What is the name of the VS code theme used by Carberra

    @duchenpaul@duchenpaul2 ай бұрын
  • Great content. Thanks! 😀

    @ryanprasad2090@ryanprasad2090Ай бұрын
    • Thank you :)

      @Indently@IndentlyАй бұрын
  • Amazing🎉

    @sg8nj@sg8nj2 ай бұрын
  • finally a channel that uses a real IDE

    @GamersOutcast@GamersOutcast29 күн бұрын
  • Instead of own retry decorator, use backoff. It's also compatible with asyncio. But it's an additional dependency.

    @deadeye1982a@deadeye1982a2 ай бұрын
  • What did you use to make "->" appear as actual arrow "→" 11:18 ?

    @__shubham__@__shubham__15 күн бұрын
    • ligatures, fonts in VSCode and PyCharm support them

      @pawelabrams@pawelabrams12 күн бұрын
  • 0:49 Did pycharm create the time import for you automatically? Or was it just a jump-cut? That's really convenient if it's pycharm. I moved from pycharm to vscode when I needed the paid for features. Meh, probably vscode will do the same thing if pycharm does and I'll never bother to set it up.

    @davidmurphy563@davidmurphy5632 ай бұрын
    • Yeah it was PyCharm :)

      @Indently@Indently2 ай бұрын
    • You can enable auto imports in VS Code by clicking the curly braces next to Python in the bottom status bar and enabling import completions in the menu that pops up.

      @rmHawk765@rmHawk7656 күн бұрын
    • @@rmHawk765 Huh, it works! Hats off, thanks so much!

      @davidmurphy563@davidmurphy5636 күн бұрын
  • Can you help me understand how is the @atexit.register functionality different from Context Manager functionality in Python?

    @RS-vu5um@RS-vu5um2 ай бұрын
    • Context managers are for cleanly disposing resources like files and database connections when they're no longer needed. This even happens when an exception is thrown in a "with" block. atexit is for global cleanup at the end of the program, which is usually not needed with small scripts.

      @D0Samp@D0Samp2 ай бұрын
    • functilonally atexit is placing your whole program in a context manager and running the supplied function in the `finally` block

      @prosodyspeaks4036@prosodyspeaks403624 күн бұрын
  • The sponsor shout out was the best lol 😂😆😂

    @crosby3108@crosby31082 ай бұрын
    • Absolutely epic😎

      @shreyasj6437@shreyasj64372 ай бұрын
  • Retry is already done by the requests library. Cache clear was interesting

    @tincustefanlucian7495@tincustefanlucian74952 ай бұрын
  • Shout-out to the funcy library, while we're here!

    @jftsang@jftsang2 ай бұрын
  • The connect() function does not return, because of the raise. The correct typing should be -> NoReturn

    @PR0MINENCE@PR0MINENCEАй бұрын
  • If the computation of a function is fixed and it will result in the same result everytime, why would I want to use cache and not just store the output in a variable?

    @TheBobi321@TheBobi321Ай бұрын
    • Because what you're talking about is a constant, and creating a constant for every single input scenario is just not ideal, and probably not possible due to the infinite amount of possible inputs.

      @Indently@IndentlyАй бұрын
  • It would be helpful if you showed the decorator code in the video as well in video.

    @hodiks@hodiks2 ай бұрын
  • 1:37 17| if retries LT 1 or delay LTE 0: 18| raise ValueError('Are you high, mate?') has me ROFL'ing!

    @DerMarkus1982@DerMarkus1982Ай бұрын
  • So these aren't 5 Python decorators, they're 5 decorators written by your average Python fan.

    @mallninja9805@mallninja9805Ай бұрын
    • Cache and atexit are part of the standard library.

      @AWriterWandering@AWriterWandering6 күн бұрын
  • These are cool, thanks. Although it is my personal opinion that retry and get_time shouldn't be decorators, you could just call the higher-order function whenever you need it instead of affecting the original function.

    @spaghettiking653@spaghettiking6532 ай бұрын
    • Are the two not equivalent? Except the decorator influences all calls to the wrapped function vs changing the call site online influences one. A decorator is just a higher order function?

      @DrGreenGiant@DrGreenGiant2 ай бұрын
    • ​@@DrGreenGiantThat is exactly what I mean, I just think it's better to keep your functions less coupled and just use the "decorator" as a normal function, so e.g. when you want to test your code that runs 3 times, you can work with the original function that runs once and not the version that runs 3 times or whatever.

      @spaghettiking653@spaghettiking6532 ай бұрын
    • @@spaghettiking653 ah I see what you mean, yes. I guess it depends on the use case. I can imagine a worker function that is being sent to a pool, for example, and it would be probably easier to temporarily decorate the worker, than to change the call site. Especially if there is already some higher order stuff going on with partials, for example. But like you say, I can imagine many other cases where it would be much better to wrap the call site rather than the definition. More food for thought, ty!

      @DrGreenGiant@DrGreenGiant2 ай бұрын
    • @@DrGreenGiant Ty yourself, I didn't give much thought to threads or any other use cases like that :)

      @spaghettiking653@spaghettiking6532 ай бұрын
  • nice =D

    @dipereira0123@dipereira01232 ай бұрын
  • I want pip install idently 😊

    @conceptsintamil@conceptsintamil2 ай бұрын
  • Python decorators are a lot less cool if you have to step into while debugging ... ;) I actually now prefer utility-functions with a lambda, or resources.

    @falklumo@falklumo2 ай бұрын
  • My favourite is @mark from pytest

    @rondamon4408@rondamon44082 ай бұрын
  • Just using memory is not a memory leak

    @black-snow@black-snow2 ай бұрын
    • I don't remember anyone stating that :)

      @Indently@Indently2 ай бұрын
    • 4:40

      @black-snow@black-snow2 ай бұрын
    • @cache internally builds a mapping (essentially a dict, but a bit fancier) between the inputs and outputs of each of your function calls. Since this creates a reference to those objects, they don't get garbage collected as long as the function is around, which is typically for the lifetime of the program, long after you're done with them. This can be nasty if you @cache an object method, it prevents the object from being garbage collected at all.

      @jftsang@jftsang2 ай бұрын
    • Good time stamp, but I said: "can lead to memory leaks".

      @Indently@Indently2 ай бұрын
  • Your s good as it cones

    @funnyvideo8677@funnyvideo86772 ай бұрын
  • retrying is a python module which is present already

    @amankrpandey1@amankrpandey12 ай бұрын
    • If you find it remember to share it with the rest of us :)

      @Indently@Indently2 ай бұрын
    • Tenacity is a Python package that implements a retry decorator

      @dreww5866@dreww58662 ай бұрын
    • pip install retrying

      @amankrpandey1@amankrpandey1Ай бұрын
    • Hope it helps ;).. love your content! Learned a lot from it. Keep sharing your knowledge!!

      @amankrpandey1@amankrpandey1Ай бұрын
    • Ahaha, I didn't know you meant "retrying" as in that was the module name, thanks for sharing!

      @Indently@IndentlyАй бұрын
  • A good set, but I was a little disappointed because some things were not called by their proper names: cache(memoization). Also surprised that wraps from functools wasn't mentioned.

    @yurass1368@yurass136819 күн бұрын
  • 1:37 Are you high, mate? this is the kind of stuff I do for side cases in functions I give it a casual error 💀

    @LambdaCreates@LambdaCreates2 ай бұрын
  • You don’t count the amount of vowels. You count the number of vowels. For some reason this distinction, which is elementary school grammar, has complete collapsed within the last 2 years. Same from less/fewer.

    @DrDeuteron@DrDeuteronАй бұрын
    • Thanks for the English lesson :)

      @Indently@IndentlyАй бұрын
    • You clearly know what he meant

      @typeer@typeer21 күн бұрын
  • Wow, deprecated and atexit.register ones are really useful Gonna use them in my project, thank you❤

    @atommax_1676@atommax_16762 ай бұрын
  • 2:43 : wait, didn’t you say at the start of the video that it was sponsored by indently? Then why do you say it isn’t sponsored?🩳

    @drdca8263@drdca82632 ай бұрын
KZhead