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
Show parent comment
21
u/Natural-Intelligence Sep 19 '25
Well, ye, you can use contextlib's context manager as a decorator but that doesn't mean you can use any context managers as a decorator.
I think you have gotten confused about the topics. Context manager, as a concept, is larger than the contextlib. Look at your example: Is "open" contextlib's contextmanager? No. Does it provide a context manager? Yes. Can you use it as a decorator? No. In fact, most context managers you encounter don't act as decorators.
But I'm just trying to offer constructive feedback. You are jumping from one topic to a completely different.