2025, Oct 19 20:00

Avoid Conflicting Timeouts in Python Selenium: Use sys.maxsize with WebDriverWait under @timeout

Learn why WebDriverWait can’t be endless, and how to use sys.maxsize under a Python @timeout decorator to centralize timeout control in Selenium. See the fix.

When a Python function is wrapped with @timeout(), adding Selenium WebDriverWait inside that function often feels redundant. The decorator already enforces a global cap, so the natural question appears: can WebDriverWait be configured with no timeout at all?

Problem setup

Consider a function governed by a top-level timeout that still uses WebDriverWait. The wait inside may expire before the decorator does, which defeats the purpose of centralizing timeout control.

from selenium.webdriver.support.wait import WebDriverWait

@timeout()
def run_task(client):
    inner_wait = WebDriverWait(client, timeout=10)
    return inner_wait

What’s really happening and why

WebDriverWait requires an explicit timeout. A true "never-ending" wait is not supported. If the goal is to avoid premature expiration inside WebDriverWait because a broader function-level timeout handles the limit, the closest practical approach is to set an extremely large timeout value so that, for all intents and purposes, WebDriverWait does not time out on its own.

Solution

The workaround is to pass an unreasonably large timeout value. Using sys.maxsize is a straightforward way to make WebDriverWait behave as if it has no timeout, while still satisfying the API’s requirement.

import sys
from selenium.webdriver.support.wait import WebDriverWait

@timeout()
def execute_job(driver_ref):
    long_wait = WebDriverWait(driver_ref, timeout=sys.maxsize)
    return long_wait

Why this matters

Keeping the timeout policy consistent helps avoid unpredictable behavior. If a function-level @timeout() rule is in charge, letting WebDriverWait expire earlier can lead to confusing failures. Enforcing a single, top-level timeout keeps the flow clear and reduces friction during debugging.

Takeaways

WebDriverWait always needs a timeout and cannot wait forever. If the function-level @timeout() governs execution time, set WebDriverWait to a very large value, such as sys.maxsize, to prevent it from timing out independently. This aligns the waiting strategy with a single point of control and avoids conflicting limits.

The article is based on a question from StackOverflow by Geoff Alexander and an answer by Corey Goldberg.