Skip to content

Conversation

@cgoldberg
Copy link
Member

@cgoldberg cgoldberg commented Nov 13, 2025

User description

🔗 Related Issues

#15697

💥 What does this PR do?

This PR improves Python type hints to use union types that are available in Python 3.10+:

This syntax is preferred over Optional and Union in newer versions of Python.

This PR also replaces several type annotations from typing module with native types, and a few other modernizations.

🔄 Types of changes

  • Bug fix (backwards compatible)
  • Modernization

PR Type

Enhancement


Description

  • Replace Optional and Union with PEP 604 union syntax (|)

  • Move Callable import from typing to collections.abc

  • Replace typing.List with native list type annotation

  • Remove unused imports and clean up type hints across codebase


Diagram Walkthrough

flowchart LR
  A["typing.Optional<br/>typing.Union"] -->|"Replace with"| B["PEP 604<br/>Union Syntax"]
  C["typing.Callable"] -->|"Move to"| D["collections.abc"]
  E["typing.List"] -->|"Replace with"| F["Native list"]
  B --> G["Modernized<br/>Type Hints"]
  D --> G
  F --> G
Loading

File Walkthrough

Relevant files
Enhancement
20 files
browsing_context.py
Replace Optional/Union with PEP 604 syntax                             
+37/-36 
exceptions.py
Modernize exception class type hints                                         
+15/-15 
webdriver.py
Update WebDriver type hints to PEP 604                                     
+34/-34 
relative_locator.py
Modernize RelativeBy class type hints                                       
+20/-20 
storage.py
Update storage module type annotations                                     
+28/-28 
emulation.py
Modernize emulation module type hints                                       
+25/-25 
input.py
Update input module with PEP 604 syntax                                   
+14/-14 
expected_conditions.py
Move Callable import and modernize type hints                       
+17/-17 
script.py
Update script module type annotations                                       
+18/-18 
generate.py
Modernize CDP generator type hints                                             
+21/-20 
client_config.py
Update ClientConfig type hints                                                     
+16/-17 
options.py
Modernize Firefox options type hints                                         
+7/-7     
virtual_authenticator.py
Update authenticator type annotations                                       
+7/-7     
action_builder.py
Modernize action builder type hints                                           
+7/-7     
print_page_options.py
Update print options type hints                                                   
+5/-5     
pointer_actions.py
Modernize pointer actions type hints                                         
+5/-6     
utils.py
Update utility functions type hints                                           
+5/-6     
options.py
Modernize Chromium options type hints                                       
+5/-5     
wheel_input.py
Update wheel input type annotations                                           
+3/-4     
browser.py
Modernize browser module type hints                                           
+7/-7     
Additional files
44 files
options.py +3/-4     
remote_connection.py +2/-3     
service.py +4/-5     
webdriver.py +2/-3     
remote_connection.py +2/-3     
service.py +6/-7     
webdriver.py +4/-5     
input_device.py +2/-2     
interaction.py +1/-2     
pointer_input.py +3/-3     
wheel_actions.py +1/-2     
common.py +1/-2     
permissions.py +2/-3     
session.py +6/-7     
webextension.py +1/-2     
by.py +2/-2     
account.py +1/-2     
dialog.py +2/-3     
log.py +2/-2     
options.py +4/-5     
selenium_manager.py +1/-2     
service.py +6/-6     
remote_connection.py +2/-3     
service.py +5/-6     
webdriver.py +2/-3     
remote_connection.py +2/-3     
service.py +5/-6     
webdriver.py +2/-3     
service.py +6/-7     
webdriver.py +2/-3     
fedcm.py +1/-2     
file_detector.py +3/-4     
remote_connection.py +8/-9     
switch_to.py +2/-3     
utils.py +2/-2     
remote_connection.py +2/-3     
service.py +4/-5     
webdriver.py +2/-3     
wait.py +5/-4     
service.py +4/-5     
webdriver.py +1/-2     
service.py +3/-4     
webdriver.py +1/-2     
remote_connection_tests.py +1/-1     

@selenium-ci selenium-ci added C-py Python Bindings B-devtools Includes everything BiDi or Chrome DevTools related B-support Issue or PR related to support classes labels Nov 13, 2025
@cgoldberg cgoldberg removed B-devtools Includes everything BiDi or Chrome DevTools related B-support Issue or PR related to support classes labels Nov 13, 2025
@SeleniumHQ SeleniumHQ deleted a comment from selenium-ci Nov 13, 2025
@SeleniumHQ SeleniumHQ deleted a comment from qodo-merge-pro bot Nov 13, 2025
@SeleniumHQ SeleniumHQ deleted a comment from qodo-merge-pro bot Nov 13, 2025
Copy link
Member

@navin772 navin772 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@cgoldberg cgoldberg merged commit e19680e into SeleniumHQ:trunk Nov 16, 2025
22 checks passed
@cgoldberg cgoldberg deleted the py-310-type-improvements branch November 16, 2025 23:50
@qodo-merge-pro
Copy link
Contributor

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
No new logging: The PR primarily updates type hints and signatures without introducing or modifying
logging of critical actions, so it neither adds nor clearly omits required audit trails.

Referred Code
    """
    return self.execute("executeCdpCommand", {"cmd": cmd, "params": cmd_args})["value"]

def execute(self, driver_command: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
    """Sends a command to be executed by a command.CommandExecutor.

    Args:



 ... (clipped 158 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Error context: Type hint refactors do not change behavior, but no additional edge-case handling or
contextual error improvements were added alongside signature changes.

Referred Code
    """Base webdriver exception."""

    def __init__(
        self, msg: Any | None = None, screen: str | None = None, stacktrace: Sequence[str] | None = None
    ) -> None:
        super().__init__()
        self.msg = msg
        self.screen = screen
        self.stacktrace = stacktrace

    def __str__(self) -> str:
        exception_msg = f"Message: {self.msg}\n"
        if self.screen:
            exception_msg += "Screenshot: available via screen\n"
        if self.stacktrace:
            stacktrace = "\n".join(self.stacktrace)
            exception_msg += f"Stacktrace:\n{stacktrace}"
        return exception_msg


class InvalidSwitchToTargetException(WebDriverException):


 ... (clipped 94 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status:
No logging change: The PR introduces no new logging and thus does not demonstrate adherence to structured,
sensitive-data-safe logging in modified paths.

Referred Code
    return f"{host}:{port}"


def is_connectable(port: int, host: str | None = "localhost") -> bool:
    """Tries to connect to the server at port to see if it is running.

    Args:
        port: port number
        host: hostname or IP
    """
    socket_ = None
    try:
        socket_ = socket.create_connection((host, port), 1)
        result = True
    except _is_connectable_exceptions:
        result = False
    finally:
        if socket_:
            try:
                socket_.shutdown(socket.SHUT_RDWR)
            except Exception:


 ... (clipped 10 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Validation unchanged: Changes are to type annotations and defaults (e.g., optional parameters) without added
input validation or sanitization logic; security posture appears unchanged but not
enhanced.

Referred Code
def set_geolocation_override(
    self,
    coordinates: GeolocationCoordinates | None = None,
    error: GeolocationPositionError | None = None,
    contexts: list[str] | None = None,
    user_contexts: list[str] | None = None,
) -> None:
    """Set geolocation override for the given contexts or user contexts.

    Args:
        coordinates: Geolocation coordinates to emulate, or None.
        error: Geolocation error to emulate, or None.
        contexts: List of browsing context IDs to apply the override to.
        user_contexts: List of user context IDs to apply the override to.

    Raises:
        ValueError: If both coordinates and error are provided, or if both contexts
            and user_contexts are provided, or if neither contexts nor
            user_contexts are provided.
    """


 ... (clipped 130 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants