@@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!
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!
Here is the link to the generator video ;)
ruclips.net/video/LjBa9sfJh7U/видео.html
oops -- thanks!
good stuff!!, as usual.
Great video! However shouldn't the 'after' part go into the `finally` block in the exception handling in the `@contextmanager` example?
it depends if it wants to do "after" in exceptional cases or not -- usually you do but not always
@@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!
Thanks. In which cases is it useful to write context managers ?
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
@@anthonywritescode closing properly files or networks, no other useful cases ?
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!
Do you have to use the contextlib annotation? Won't python make it a generator just by having a yield statement?
a generator isn't a contextmanager -- the decorator converts the 1-generator into a context manager
my guess is that you'll be using contextlib, let's see :D
Edit: ayy, Fluent Python taught me well