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.

Class-Based vs Function-Based Context Managers

Give Feedback

After writing class-based and function-based context managers, this lesson compares both of them and names certain trade-offs that might occur.

ashokbayana369 on May 7, 2019

Nice explanation of Context Managers..:)

Wiggers on May 8, 2019

I like this as I only looked at it because I didn’t know what it was and now I understand!

Dan Bader RP Team on May 9, 2019

You’re welcome, that’s great to hear :)

Tim Pozza on May 12, 2019

Detailing the various approaches in context really helps to understand the concept and how one might arrive at an implementation with respect to their own, or a community’s coding knowledge. The possible trouble of using an obscure approach since having its roots revealed is avoided by the awareness of what’s going on and how those who don’t know might get lost in an implementation that’s too far removed syntactically from the underlying logic. Without these videos even saying that would be impossible. Thanks for yet another insight.

rikhuygen on May 15, 2019

Very nice tutorial which clearly explains the concept.

I wonder however how useful this is for database or socket connections which are usually ‘open’ for a longer time, especially sockets. Using this scheme every time you want to write/ read to a socket is probably very expensive. Is there a pattern to use here or is this just not the task for a ‘with’ statement?

ALXTheMaster on July 31, 2019

finally understood the concepts, thanks :)

leesmith4044 on Aug. 10, 2019

Please provide other examples where a context manager is useful besides dealing with files.

mikesult on March 3, 2020

Nice to get an understanding of the context manager protocol and how some of the dunder methods work. Thank you for another great tutorial.

legendarylisak on March 29, 2020

Great explanation of the generator and contextmanager.

Cristian Palau on April 9, 2020

Very interesting. Thanks Dan!

Liam Pulsifer RP Team on May 5, 2020

Nice work as always, Dan :)

pwells314 on June 14, 2020

Dan,

I understand the “obvious” vs “elegant” argument, but is there any behavioral or performance reason to prefer one approach over the other?

Thanks Paul

Ghani on Oct. 15, 2020

Great course; thanks Dan.

Become a Member to join the conversation.