Locked learning resources

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

Unlock This Lesson

Locked learning resources

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

Unlock This Lesson

Class-Based vs Function-Based Context Managers

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

For more information on context managers, check out Context Managers and Python’s with Statement as either a written tutorial or a video course.

00:00 So, with this technique, using contextlib and using the @contextmanager decorator, you can write some of these context managers a lot quicker.

00:10 I guess the downside is that for someone to understand this piece of code, they would have to have some basic knowledge about decorators and they would also have to have some basic knowledge about how generators work in Python, right? So, when you compare that with the class-based implementation, you could actually say, “Hey, the class-based implementation communicates what’s going on much more clearly for someone who’s not an expert at Python.” So depending, you know, how your team feels about this, and what everyone’s expertise level is, it’s kind of a fine balance with what concepts you want to pull into this.

00:42 Personally, I think this is pretty beautiful, right? This is awesome. This is very Pythonic. But on the other hand, it requires someone to understand many, many more concepts in order to actually understand what’s going on looking at this. I mean, they’re going to still use it the same way, so they might not care, but I just wanted to mention that because, in my mind, code always needs to communicate what’s going on. Code is communication.

01:06 And this is a great example where you can see where the trade-offs are, right? And I can’t make those decisions for you, but it will be something that you need to decide within the context of your team, the project you’re working on, and so on, right?

01:19 I just wanted to mention that. All right, so I hope that gave you a good overview of how these context managers work, how the with statement works behind the scenes, and what you can do with them.

Avatar image for ashokbayana369

ashokbayana369 on May 7, 2019

Nice explanation of Context Managers..:)

Avatar image for Wiggers

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!

Avatar image for Dan Bader

Dan Bader RP Team on May 9, 2019

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

Avatar image for Tim Pozza

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.

Avatar image for rikhuygen

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?

Avatar image for ALXTheMaster

ALXTheMaster on July 31, 2019

finally understood the concepts, thanks :)

Avatar image for leesmith4044

leesmith4044 on Aug. 10, 2019

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

Avatar image for mikesult

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.

Avatar image for legendarylisak

legendarylisak on March 29, 2020

Great explanation of the generator and contextmanager.

Avatar image for Cristian Palau

Cristian Palau on April 9, 2020

Very interesting. Thanks Dan!

Avatar image for Liam Pulsifer

Liam Pulsifer RP Team on May 5, 2020

Nice work as always, Dan :)

Avatar image for pwells314

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

Avatar image for Ghani

Ghani on Oct. 15, 2020

Great course; thanks Dan.

Avatar image for michael

michael on May 29, 2021

Hi Dan,

Many thanks for clear explanation. I understand that the with statement simplifies exception handling. But if an error occurs, what is the typical pattern for dealing with them (e.g. in database connections)? Put the with-statement in an additional try-except clause?

Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on May 31, 2021

@michael That’s correct. The most common way to handle exceptions raised in a with clause would be to wrap the entire clause in another try..except clause:

try:
    with open(path) as file:
        pass  # Raise exception
except SomeException as ex:
    pass  # Handle the exception
Avatar image for Pavneet Ghai

Pavneet Ghai on May 23, 2022

I wish we had example on SQLite db.

Avatar image for Martin Breuss

Martin Breuss RP Team on May 23, 2022

@Pavneet Ghai what are you looking for regarding SQLite? Did you check out some the tutorials we have on it:

Become a Member to join the conversation.