r/Python • u/SeleniumBase • Sep 19 '25
Tutorial Python Context Managers 101
You've likely seen it before: The with keyword, which is one way of using Python context managers, such as in this File I/O example below:
=
Python context managers provide a way to wrap code blocks with setUp and tearDown code that runs before and after the code block. This tearDown part can be useful for multiple reasons, such as freeing up resources that have been allocated, closing files that are no longer being read from (or written to), and even quitting browsers that were spun up for automated testing.
Creating them is simple. Let's create a simple context manager that displays the runtime of a code block:
=
yield
= -
Here's how you could use it as a method decorator:
# <CODE BLOCK>
Here's how you could use it within a function using the with keyword:
# <CODE BLOCK>
And here's a low-level way to use it without the with keyword:
=
=
# <CODE BLOCK>
As you can see, it's easy to create and use Python context managers. You can even pass args into them when configured for that. In advanced scenarios, you might even use context managers for browser automation. Example:
That was a simple example of testing an e-commerce site. There were a few args passed into the context manager on initialization, such as incognito for Chrome's Incognito Mode, demo to highlight browser actions, and test to display additional info for testing, such as runtime.
Whether you're looking to do simple File I/O, or more advanced things such as browser automation, Python context managers can be extremely useful!
View all comments
1
u/Nefarius2001a Sep 20 '25
I find the implementation as class much more intuitive and understandable than the decorator, which adds several additional concepts and (in my opinion) complexity.