Contextlib and Its Classes

Let's explore classes of contextlib.

There are multiple classes of contextlib. Let’s talk about them one by one.

  • contextlib.closing
  • contextlib.suppress(*exceptions)
  • contextlib.redirect_stdout / redirect_stderr
Press + to interact

contextlib.closing

The contextlib module comes with some other handy utilities. The first one is the closing class which will close the db upon the completion of code block. The Python documentation gives an example that’s similar to the following one:

Press + to interact
from contextlib import contextmanager
@contextmanager
def closing(db):
try:
yield db.conn()
finally:
db.close()

Basically what we’re doing is creating a closing function that’s wrapped in a contextmanager. This is the equivalent of what the closing class does. The difference is that instead of a decorator, we can use the closing class itself in our with statement. Let’s take a look:

Access this course and 1400+ top-rated courses and projects.