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

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Function-Based Context Managers With "contextlib"

Give Feedback

In the last two lessons you worked with a class-based context manager. In this video you’ll learn how to implement a function-based context manager using Python’s contextlib module.

Gilles Consulting 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.