import contextlib @contextlib.contextmanager def get_driver_context(): with webdriver.Chrome(service=Service(driver_path), options=options) as b: b.implicitly_wait(10) b.set_window_position(0, 0) b.set_window_rect(0, 0, 1000, 600) yield b with get_driver_context() as b: b.get("https://www.python.org") time.sleep(3)