Member-only story
All You Need To Know About Context Managers In Python
Learn the magic behind “with” statements in Python with examples
Regarded as an obscure feature by some, the with
statement in Python is often only used when dealing with file operations. Below is an example that shows you how to read and write a file with Python’s built-in open
function:
For the most part, all people knew was that using the with
statement is the preferred way to manage files rather than using the close
method.
The fact is, most people couldn’t be bothered enough to peek behind the scene of what is happening behind the scenes. Here’s a tip: the underlying protocol is known as a context manager.
To me, it was all magic. Honestly, who would be bothered without knowing why should we ever use it?
In this article, I am going to share with you why we should use context manager along with some practical use cases involving database connections. You could probably refactor some part of your codebase to use context manager with the with
statement as well. Let’s dive into it!
TL;DR
- Avoid leaving any files or database connections open as they are limited
- Context manager allows us to better manage these resources by telling an object what to do when created or destroyed
- The use of
with
statement allows us to reduce code duplication
Whys
Resource management
If I were to summarize it, it would be just two words: resource management.
When building any application, we can use resources like file operations and database connections. Here’s a key takeaway: these resources are limited.
Often, we would need to “release” these resources after using them. As an example, whenever we open a file from our filesystem, we need to explicitly close the file when we are done using it.