Did You Know Context Managers Aren’t Just for File Operations?

When you first learn about context managers in Python — specifically the withas… syntax — they’re usually introduced through file handling examples. That’s no surprise, since managing files safely is one of the most common use cases.

However, context managers can be useful in a wide variety of scenarios beyond just opening and closing files.

Below is an example that demonstrates exactly that — showing how context managers can be used for something entirely different: measuring execution time. We implement this in two different ways.

The first version defines a class with the __enter__ and __exit__ methods. The second uses a generator function decorated with the contextmanager decorator from the standard library’s contextlib module. In both cases, we use the perf_counter() function from the time module to measure elapsed time.

For testing, we use both context managers inside a with block and simulate a delay with time.sleep(). In one of the test cases, we intentionally raise an exception halfway through to demonstrate how the context manager still behaves correctly — printing the elapsed time even when an error occurs.

Code Example 1 – Class-based context manager

Code Example 2 – Context manager using a decorated generator function

As you can see, both versions correctly measure and print the elapsed time — even when an exception is raised. This demonstrates just how versatile and reliable context managers can be, and why it’s worth mastering them.

You can find more advanced examples in the e-book Python Knowledge Building Step-by-Step, which explores how context managers can be used beyond file operations. The book focuses on helping readers understand the underlying concept and mechanics of context managers, so they can confidently apply this elegant Python feature to a wide range of problems.

Interested in the e-book Python Knowledge Building Step by Step: From the Basics to Your First Desktop Application?