with + context managers (part2: the easy way) (intermediate) anthony explains

Поделиться
HTML-код
  • Опубликовано: 8 ноя 2024

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

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

    Here is the link to the generator video ;)
    ruclips.net/video/LjBa9sfJh7U/видео.html

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

    good stuff!!, as usual.

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

    Great video! However shouldn't the 'after' part go into the `finally` block in the exception handling in the `@contextmanager` example?

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

      it depends if it wants to do "after" in exceptional cases or not -- usually you do but not always

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

      @@anthonywritescode Right, I only mentioned this because the whole topic started with the example of opening files and gracefully closing them with the open() contextmanager, so in this case the finally block would've been closer to this in the example. Anyways, Great explanation and thanks for the awesome contents!

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

    Thanks. In which cases is it useful to write context managers ?

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

      part 1 talks about this more in detail -- the beginning of that video has some advice on why you'd write one: ruclips.net/video/ExdtNMnP24I/видео.html

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

      @@anthonywritescode closing properly files or networks, no other useful cases ?

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

      those were just examples, any time you want to do something before and/or after some other code. some examples are for decorators, controlling cleanup, mocking, fixtures, etc. etc. I've even used it for doing wrapper elements in html templating!

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

    Do you have to use the contextlib annotation? Won't python make it a generator just by having a yield statement?

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

      a generator isn't a contextmanager -- the decorator converts the 1-generator into a context manager

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

    my guess is that you'll be using contextlib, let's see :D
    Edit: ayy, Fluent Python taught me well