playwright-python icon indicating copy to clipboard operation
playwright-python copied to clipboard

[Feature] `__enter__`/`__exit__` on `Browser`

Open jamesbraza opened this issue 1 year ago • 1 comments

I have python-playwright with version 1.41.0, and the below code:

from playwright.sync_api import sync_playwright


with sync_playwright() as p:
    browser = p.chromium.launch()
    ...  # Use browser
    browser.close()

Ideally, one can use a context manager to automate the close() call:

from playwright.sync_api import sync_playwright


with sync_playwright() as p, p.chromium.launch() as browser:
    ...  # Use browser

Thank you for your consideration

jamesbraza avatar Jan 22 '24 21:01 jamesbraza

One can get pretty close with contextlib.closing:

import contextlib

from playwright.sync_api import sync_playwright


with sync_playwright() as p, contextlib.closing(p.chromium.launch()) as browser:
    ...  # Use browser

However, it would be nice if this was upstreamed to Browser itself

jamesbraza avatar Jan 22 '24 22:01 jamesbraza