{"record":{"id":"5b293d539eb1624e","repo":"SeleniumHQ/selenium","slug":"fn-name-must-be-called-in-a-connection-context","errorCode":null,"errorMessage":"{fn_name}() must be called in a connection context.","messagePattern":"(.+?)\\(\\) must be called in a connection context\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"py/private/cdp.py","lineNumber":93,"sourceCode":"        selenium_logger.debug(\"Falling back to loading `devtools`: v%s\", latest)\n        devtools = importlib.import_module(f\"{base}{latest}\")\n        return devtools\n\n\n_connection_context: contextvars.ContextVar = contextvars.ContextVar(\"connection_context\")\n_session_context: contextvars.ContextVar = contextvars.ContextVar(\"session_context\")\n\n\ndef get_connection_context(fn_name):\n    \"\"\"Look up the current connection.\n\n    If there is no current connection, raise a ``RuntimeError`` with a\n    helpful message.\n    \"\"\"\n    try:\n        return _connection_context.get()\n    except LookupError:\n        raise RuntimeError(f\"{fn_name}() must be called in a connection context.\")\n\n\ndef get_session_context(fn_name):\n    \"\"\"Look up the current session.\n\n    If there is no current session, raise a ``RuntimeError`` with a\n    helpful message.\n    \"\"\"\n    try:\n        return _session_context.get()\n    except LookupError:\n        raise RuntimeError(f\"{fn_name}() must be called in a session context.\")\n\n\n@contextmanager\ndef connection_context(connection):\n    \"\"\"Context manager installs ``connection`` as the session context for the current Trio task.\"\"\"\n    token = _connection_context.set(connection)","sourceCodeStart":75,"sourceCodeEnd":111,"githubUrl":"https://github.com/SeleniumHQ/selenium/blob/aa36b38e696a0909e973bdf5e2f9031ffe842c4b/py/private/cdp.py#L75-L111","documentation":"Raised as a RuntimeError by get_connection_context(fn_name) when the contextvars.ContextVar _connection_context has no value set (LookupError). The CDP module uses contextvars to implicitly pass the active connection through the call stack; CDP API functions call get_connection_context to retrieve it. If called outside a connection_context() or async with connection block, there is no current connection and the function cannot dispatch commands.","triggerScenarios":"Calling a CDP API function that relies on get_connection_context() — such as dom.get_document() or any module-level CDP call — outside of a `with connection_context(conn):` block or outside an `async with conn:` session. The ContextVar has no default and was never set in the current context.","commonSituations":"Calling a CDP helper function at the wrong scope (before entering the connection context); refactoring code and moving a CDP call outside the `async with` block; using CDP functions in a callback or different task that does not inherit the contextvar; forgetting to wrap calls in the context manager.","solutions":["Wrap all CDP API calls inside `async with connection:` or `with connection_context(conn):` so the ContextVar is set.","If calling from a separate task or callback, explicitly re-establish the context: `with connection_context(conn):` inside that task.","Pass the connection explicitly to methods that accept it rather than relying on the implicit context."],"exampleFix":"# before\nasync def main():\n    conn = await Connection.create(url)\n    doc = await dom.get_document()  # RuntimeError: no connection context\n\n# after\nasync def main():\n    conn = await Connection.create(url)\n    async with conn:\n        doc = await dom.get_document()  # context is set","handlingStrategy":"try-catch","validationCode":"# Ensure you are inside a connection context before calling CDP functions\nfrom selenium.webdriver.common.bidi.cdp import get_connection_context\ntry:\n    conn = get_connection_context('check')\nexcept RuntimeError:\n    # enter a connection context first\n    pass","typeGuard":null,"tryCatchPattern":"try:\n    await dom.get_document()\nexcept RuntimeError as e:\n    if 'connection context' in str(e):\n        async with conn:\n            await dom.get_document()\n    else:\n        raise","preventionTips":["Always wrap CDP calls in `async with conn:` or `with connection_context(conn):`.","Do not call CDP module-level functions outside the connection context.","For background tasks, re-establish the context inside the task."],"tags":["python","cdp","contextvars","connection","trio"],"backgroundTag":null,"analyzedSha":"aa36b38e696a0909e973bdf5e2f9031ffe842c4b","analyzedAt":"2026-08-14T02:32:32.244Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}