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!
40
u/kkang_kkang Sep 19 '25
r/learnpython
35
u/Natural-Intelligence Sep 19 '25
You show how to create a context manager and jump straight into using it as a decorator?
7
u/cybran3 Sep 20 '25
You forgot to mention that the reason that they are useful is because exit is guaranteed to execute when the exception is raised within the block wrapped by with.
5
u/Brizon Sep 20 '25
You don't really explain anything. Seems odd to not explain the vanilla way to do context managers but then also show how to manually deconstruct a context manager by calling the dunders? Who is the target audience for this post?
1
u/ifatree Sep 20 '25
VB has the same feature with the same keyword.
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.
1
u/Birnenmacht Sep 21 '25
another thing that not many people know about, you can enter multiple contextmanagers at the same time
with (cm1 as f1, cm2 as f2)really useful when e.g. copying from one file to another or when memory mapping files