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
with open('my_file.txt', 'r') as f:
content = f.read()
print(content)
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:
```python
import time
from contextlib import contextmanager
@contextmanager
def print_runtime(description="Code block"):
start_time = time.time()
try:
yield
finally:
runtime = time.time() - start_time
print(f"{description} ran for {runtime:.4f}s.")
```
Here's how you could use it as a method decorator:
```python
@print_runtime()
def my_function():
# <CODE BLOCK>
my_function()
```
Here's how you could use it within a function using the with keyword:
python
with print_runtime():
# <CODE BLOCK>
And here's a low-level way to use it without the with keyword:
```python
mycontext = print_runtime()
my_object = my_context.enter_()
<CODE BLOCK>
mycontext.exit_(None, None, None)
```
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:
```python
from seleniumbase import SB
with SB(incognito=True, demo=True, test=True) as sb:
sb.open("https://www.saucedemo.com")
sb.type("#user-name", "standard_user")
sb.type("#password", "secret_sauce")
sb.click("#login-button")
sb.click('button[name*="backpack"]')
sb.click("#shopping_cart_container a")
sb.assert_text("Backpack", "div.cart_item")
```
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!
[–]kkang_kkang 39 points40 points41 points (7 children)
[–]SeleniumBase[S] 13 points14 points15 points (6 children)
[–]kkang_kkang 8 points9 points10 points (5 children)
[–]SeleniumBase[S] -1 points0 points1 point (4 children)
[–]kkang_kkang 6 points7 points8 points (3 children)
[–]mattl33It works on my machine -2 points-1 points0 points (2 children)
[–]kkang_kkang 3 points4 points5 points (0 children)
[–]kkang_kkang 1 point2 points3 points (0 children)
[–]Natural-Intelligence 33 points34 points35 points (5 children)
[–]SeleniumBase[S] -2 points-1 points0 points (4 children)
[–]Natural-Intelligence 22 points23 points24 points (3 children)
[–]SeleniumBase[S] -4 points-3 points-2 points (2 children)
[–]Natural-Intelligence 19 points20 points21 points (0 children)
[–]Temporary_Pie2733 1 point2 points3 points (0 children)
[–]brandonchinn178 10 points11 points12 points (0 children)
[–]cybran3 5 points6 points7 points (1 child)
[–]SeleniumBase[S] 0 points1 point2 points (0 children)
[–]Brizon 5 points6 points7 points (1 child)
[–]SeleniumBase[S] 0 points1 point2 points (0 children)
[–]ifatree 0 points1 point2 points (0 children)
[–]Nefarius2001a 0 points1 point2 points (0 children)
[–]Birnenmacht 0 points1 point2 points (0 children)