Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Function-Based Context Managers With "contextlib"

Give Feedback

Comments & Discussion

Anonymous on May 9, 2019

Hello, Thanks for you videos. very clear, even if for this one I have 2 questions:

I am wondering why you defined a generator, with a yield, instead of a return. well, it does not work with a return :) I can’t get why a generator is needed.. Could you clarify that please?

Also, if I understand properly, in you managed_file function the “try:” is taken in charge by the __enter__ function, and the finally by the __exit__ one (cf the class you defined in your previous video to reproduce the with behavior. Could you confirm if it’s correct?

Thank you in advance.

Dan Bader RP Team on May 9, 2019

I can’t get why a generator is needed.. Could you clarify that please?

Ah, the reason is that contextlib.contextmanager requires a generator :) Using a generator allows the function to be temporarily “paused” and then later resumed again for the context manager’s “exit” step. A regular function can’t do that sort of thing, hence the yield to define a generator.

Become a Member to join the conversation.