Skip to content

Conversation

@iampopovich
Copy link
Contributor

@iampopovich iampopovich commented Oct 25, 2025

User description

🔗 Related Issues

relates #11442

💥 What does this PR do?

This pull request refactors docstrings throughout several files in the Selenium Python codebase, specifically in the action_builder.py, browser.py, and browsing_context.py modules. The main focus is to standardize and modernize the documentation style by replacing sections like "Parameters", "Returns", and "Raises" with the more Pythonic "Args", direct return type descriptions, and clearer exception documentation. This improves readability and consistency for developers and users of the API.

Docstring standardization and modernization:

  • Replaced "Parameters" and "Returns" sections with "Args" and direct return type descriptions in all relevant methods across action_builder.py, browser.py, and browsing_context.py. [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

  • Updated exception documentation to use "Raises" with specific exception types, improving clarity on error handling. [1] [2] [3] [4]

Minor improvements and fixes:

  • Improved example formatting by removing unnecessary "Example" headers. [1] [2] [3] [4] [5]
  • Enhanced error propagation by chaining exceptions for better debugging.
  • Ensured all docstrings consistently describe return values and arguments for easier maintenance and usage. [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]

Overall, these changes make the codebase's documentation more uniform and accessible for both new and experienced developers.

🔧 Implementation Notes

💡 Additional Considerations

🔄 Types of changes

  • Cleanup (formatting, renaming)

PR Type

Documentation


Description

Comprehensive standardization of Python docstrings across the Selenium codebase to follow Google pydoc format:

  • Core refactoring: Converted docstrings from "Parameters/Returns/Raises" format to Google-style "Args/Returns/Raises" across 21 files
  • Removed separators: Eliminated redundant dashes and separator lines from section headers throughout BiDi modules and core classes
  • Improved formatting: Standardized parameter descriptions, return type documentation, and example sections with consistent indentation
  • Bug fix in network module: Changed _add_intercept parameter phases default from mutable empty list to None with runtime initialization
  • Enhanced type hints: Added return type annotations to find_element, find_elements, and add_file_dialog_handler methods
  • Exception handling improvements: Updated exception types (e.g., Exception to ValueError) and added exception chaining in error handling
  • Simplified documentation: Streamlined Safari options property docstrings to single-line descriptions with type annotations
  • Consistency improvements: Standardized "Notes" to "Note", improved clarity of return descriptions, and consolidated multi-line descriptions

Diagram Walkthrough

flowchart LR
  A["Old Format<br/>Parameters/Returns/Raises<br/>with separators"] -- "Refactor" --> B["Google pydoc Format<br/>Args/Returns/Raises<br/>clean sections"]
  B --> C["21 Python files<br/>updated"]
  C --> D["Core modules:<br/>WebDriver, WebElement,<br/>Options"]
  C --> E["BiDi modules:<br/>Browser, Network,<br/>Session, Storage"]
  C --> F["Support modules:<br/>Wait, Actions,<br/>Expected Conditions"]
Loading

File Walkthrough

Relevant files
Documentation
17 files
webdriver.py
Standardize docstring format to Google style guide             

py/selenium/webdriver/remote/webdriver.py

  • Standardized docstrings from "Parameters/Returns/Raises" format to
    Google-style "Args/Returns/Raises"
  • Reformatted example sections with consistent indentation and removed
    separator lines
  • Updated parameter documentation to use inline descriptions instead of
    bullet points
  • Improved consistency in return type descriptions and exception
    documentation
+244/-408
expected_conditions.py
Apply Google docstring format to expected conditions         

py/selenium/webdriver/support/expected_conditions.py

  • Converted all docstrings from "Parameters/Returns" to "Args/Returns"
    format
  • Reformatted example code blocks with consistent indentation
  • Changed "Notes" sections to "Note" for consistency with Google style
  • Improved clarity of return type descriptions
+246/-385
webelement.py
Standardize WebElement docstrings to Google format             

py/selenium/webdriver/remote/webelement.py

  • Standardized docstrings to Google-style "Args/Returns/Raises" format
  • Reformatted example sections with proper indentation and removed
    separator lines
  • Updated parameter descriptions to be more concise and inline
  • Improved consistency in return value documentation
+122/-191
browsing_context.py
Apply Google docstring format to browsing context module 

py/selenium/webdriver/common/bidi/browsing_context.py

  • Converted docstrings from "Parameters/Returns" to "Args/Returns"
    format
  • Removed separator lines (dashes) from section headers
  • Improved formatting of return type descriptions
  • Updated exception documentation format
+36/-75 
storage.py
Standardize storage module docstrings to Google format     

py/selenium/webdriver/common/bidi/storage.py

  • Standardized docstrings to Google-style "Args/Returns" format
  • Removed separator lines from section headers
  • Improved clarity of parameter and return descriptions
  • Added example section to get_cookies method
+27/-41 
session.py
Apply Google docstring format to session module                   

py/selenium/webdriver/common/bidi/session.py

  • Converted docstrings from "Parameters/Returns" to "Args/Returns"
    format
  • Removed separator lines from section headers
  • Improved formatting and clarity of descriptions
  • Updated status method docstring for better readability
+15/-19 
options.py
Standardize IE options property docstrings to Google format

py/selenium/webdriver/ie/options.py

  • Standardized docstrings for 16 property descriptors by replacing
    "Parameters" sections with "Args"
  • Simplified Usage sections with more concise formatting
  • Improved consistency in documentation style across all IE option
    properties
+102/-170
print_page_options.py
Modernize print page options docstrings to Google format 

py/selenium/webdriver/common/print_page_options.py

  • Converted "Parameters" and "Returns" sections to "Args" and "Returns"
    in Google pydoc format
  • Simplified Usage sections with cleaner formatting
  • Updated set_page_size method docstring with improved Args and Example
    sections
  • Enhanced clarity of parameter descriptions with type information
+72/-151
options.py
Standardize base options property docstrings to Google format

py/selenium/webdriver/common/options.py

  • Refactored 11 property docstrings replacing "Parameters" with "Args"
    in Google format
  • Simplified "Returns" sections with clearer descriptions
  • Fixed typo in page_load_strategy docstring (removed leading colon)
  • Consolidated multi-line docstring descriptions into single lines
+63/-161
wait.py
Modernize WebDriverWait docstrings to Google pydoc format

py/selenium/webdriver/support/wait.py

  • Converted "Attributes" section to "Args" in __init__ docstring
  • Standardized "Parameters" to "Args" and "Return" to "Returns" across 3
    methods
  • Improved Example sections with proper indentation and formatting
  • Fixed until_not docstring description to accurately reflect behavior
+48/-73 
action_builder.py
Standardize action builder docstrings to Google format     

py/selenium/webdriver/common/actions/action_builder.py

  • Converted "Parameters" sections to "Args" format in 6 methods
  • Simplified "Returns" sections with clearer type descriptions
  • Improved Example sections with consistent indentation
  • Enhanced parameter descriptions with inline type information
+31/-54 
emulation.py
Standardize emulation BiDi docstrings to Google format     

py/selenium/webdriver/common/bidi/emulation.py

  • Converted "Parameters" sections to "Args" format in 3 methods
  • Removed redundant "------" separators from "Raises" sections
  • Improved multi-line parameter descriptions with better formatting
  • Enhanced consistency in error documentation
+9/-14   
options.py
Simplify Safari options property docstrings                           

py/selenium/webdriver/safari/options.py

  • Simplified docstrings for 3 property descriptors to single-line
    descriptions
  • Added type annotations to property descriptors
  • Removed verbose Usage and Parameters sections
  • Replaced with concise descriptions of property functionality
+6/-40   
server.py
Standardize server class docstring to Google format           

py/selenium/webdriver/remote/server.py

  • Converted class docstring "Parameters" section to "Args" format
  • Improved parameter descriptions with clearer formatting
  • Enhanced consistency with Google pydoc style guidelines
+8/-15   
webextension.py
Modernize web extension BiDi docstrings                                   

py/selenium/webdriver/common/bidi/webextension.py

  • Converted "Parameters" sections to "Args" format in 2 methods
  • Removed redundant "-------" separators from "Returns" sections
  • Improved parameter description formatting and alignment
+7/-10   
permissions.py
Standardize permissions BiDi docstring format                       

py/selenium/webdriver/common/bidi/permissions.py

  • Converted "Parameters" section to "Args" format
  • Removed redundant "------" separator from "Raises" section
  • Improved parameter descriptions with better formatting
+2/-4     
common.py
Modernize common BiDi utility docstring                                   

py/selenium/webdriver/common/bidi/common.py

  • Converted "Parameters" section to "Args" format
  • Removed redundant "--------" separator from "Returns" section
  • Improved consistency with Google pydoc style
+1/-3     
Bug fix, documentation
1 files
network.py
Refactor network BiDi docstrings and fix mutable default argument

py/selenium/webdriver/common/bidi/network.py

  • Changed _add_intercept parameter phases default from empty list to
    None with runtime initialization
  • Converted docstrings from "Parameters" to "Args" format across 6
    methods
  • Updated "Returns" sections with cleaner formatting
  • Changed "Notes" to "Note" and improved exception documentation
    consistency
+36/-56 
Enhancement, documentation
1 files
shadowroot.py
Add type hints and modernize shadow root docstrings           

py/selenium/webdriver/remote/shadowroot.py

  • Added return type annotations to find_element and find_elements
    methods
  • Converted docstrings from "Parameters" to "Args" format
  • Reorganized "Returns" and "Example" sections for better readability
  • Added import for WebElement type annotation
+32/-41 
Documentation, error handling
1 files
browser.py
Clean up browser BiDi docstrings and improve error handling

py/selenium/webdriver/common/bidi/browser.py

  • Removed redundant "-------" separators from "Returns" sections in 8
    getter methods
  • Converted from_dict and create_user_context docstrings to "Args"
    format
  • Changed exception type from generic Exception to ValueError in
    remove_user_context
  • Added exception chaining with from e in from_dict error handling
+9/-25   
Documentation, enhancement
1 files
input.py
Modernize input BiDi docstrings and add type hints             

py/selenium/webdriver/common/bidi/input.py

  • Converted "Parameters" sections to "Args" format in 6 methods
  • Added return type annotation to add_file_dialog_handler method
  • Removed redundant "--------" separators from "Returns" sections
  • Improved parameter description formatting
+7/-15   

@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 Oct 25, 2025
@selenium-ci
Copy link
Member

Thank you, @iampopovich for this code suggestion.

The support packages contain example code that many users find helpful, but they do not necessarily represent
the best practices for using Selenium, and the Selenium team is not currently merging changes to them.

After reviewing the change, unless it is a critical fix or a feature that is needed for Selenium
to work, we will likely close the PR.

We actively encourage people to add the wrapper and helper code that makes sense for them to their own frameworks.
If you have any questions, please contact us

@iampopovich
Copy link
Contributor Author

@cgoldberg check please

@iampopovich iampopovich marked this pull request as ready for review October 26, 2025 00:00
@qodo-merge-pro
Copy link
Contributor

qodo-merge-pro bot commented Oct 26, 2025

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 <!-- /create_ticket --create_ticket=true -->

</details></td></tr>
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
No custom compliance provided

Follow the guide to enable custom compliance check.

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

@qodo-merge-pro
Copy link
Contributor

qodo-merge-pro bot commented Oct 26, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Fix incorrect documentation example

Correct the incorrect example for the title property in the docstring, as it
wrongly demonstrates usage on a WebElement instead of the WebDriver instance.

py/selenium/webdriver/remote/webdriver.py [461-466]

 """Returns the title of the current page.
 
 Example:
-    >>> element = driver.find_element(By.ID, "foo")
-    >>> print(element.title())
+    >>> print(driver.title)
 """
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies and fixes a misleading example in the docstring for the title property, which improves the accuracy and usability of the documentation.

Low
Correct docstring return type
Suggestion Impact:The commit updated the docstring to state "str when getting, None when setting," matching the suggestion.

code diff:

     Returns:
-        bool when getting, None when setting.
+        str when getting, None when setting.

Correct the return type in the web_socket_url docstring from bool to str to
accurately reflect that it returns a URL.

py/selenium/webdriver/common/options.py [316-328]

 web_socket_url = _BaseOptionsDescriptor("webSocketUrl")
 """Gets and Sets WebSocket URL.
 
 Usage:
     - Get: `self.web_socket_url`
     - Set: `self.web_socket_url = value`
 
 Args:
     value: str
 
 Returns:
-    bool when getting, None when setting.
+    str when getting, None when setting.
 """

[Suggestion processed]

Suggestion importance[1-10]: 3

__

Why: The suggestion correctly identifies and fixes a documentation error where the return type for web_socket_url is incorrectly stated as bool instead of str, improving the accuracy of the docstring.

Low
Clarify docstring for method behavior

Clarify the until_not docstring to state that the method waits for a "falsy"
return value, not just a False one, to more accurately describe its behavior.

py/selenium/webdriver/support/wait.py [123-127]

 def until_not(self, method: Callable[[D], T], message: str = "") -> Union[T, Literal[True]]:
-    """Wait until the method returns a value that is False.
+    """Wait until the method returns a falsy value.
 
     Calls the method provided with the driver as an argument until the
     return value evaluates to ``False``.
  • Apply / Chat
Suggestion importance[1-10]: 3

__

Why: The suggestion correctly points out that the until_not method waits for a "falsy" value, not strictly False, and proposes a docstring clarification that improves accuracy and user understanding.

Low
Improve variable name for clarity

Revert the variable name in the staleness_of example from is_stale to the
original is_element_stale for better clarity and consistency.

py/selenium/webdriver/support/expected_conditions.py [549-562]

 """Wait until an element is no longer attached to the DOM.
 
 Args:
     element: The element to wait for.
 
 Returns:
     False if the element is still attached to the DOM, true otherwise.
 
 Example:
     >>> from selenium.webdriver.common.by import By
     >>> from selenium.webdriver.support.ui import WebDriverWait
     >>> from selenium.webdriver.support import expected_conditions as EC
-    >>> is_stale = WebDriverWait(driver, 10).until(EC.staleness_of(driver.find_element(By.CLASS_NAME, "foo")))
+    >>> is_element_stale = WebDriverWait(driver, 10).until(EC.staleness_of(driver.find_element(By.CLASS_NAME, "foo")))
 """
  • Apply / Chat
Suggestion importance[1-10]: 2

__

Why: The suggestion proposes reverting a variable name in an example to its original, more descriptive form, which is a minor improvement for consistency and readability.

Low
Learned
best practice
Raise a more specific exception

Use KeyError when a specific key-like identifier is missing, aligning the raised
exception with the invalid state and Python conventions.

py/selenium/webdriver/common/bidi/network.py [84-110]

 def _remove_intercept(self, intercept=None):
     """Remove a specific intercept, or all intercepts.
 
     Args:
         intercept: The intercept to remove. Default is None.
 
     Raises:
-        ValueError: If intercept is not found.
+        KeyError: If intercept is not found.
 
     Note:
         If intercept is None, all intercepts will be removed.
     """
     if intercept is None:
         self.callbacks = {}
         for subscription in self.subscriptions.values():
             self.conn.execute(subscription)
         self.subscriptions = {}
     elif intercept in self.callbacks:
         del self.callbacks[intercept]
         cmd = command_builder("network.removeIntercept", {"intercept": intercept})
         self.conn.execute(cmd)
     else:
-        raise ValueError("Intercept not found")
+        raise KeyError("Intercept not found")

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 6

__

Why:
Relevant best practice - Validate inputs and states early with precise checks to prevent logic errors; raising the most appropriate exception type for invalid inputs.

Low
Possible issue
Fix incorrect type in example

Correct the type used for the partition argument in the get_cookies example from
PartitionKey to a valid type like BrowsingContextPartitionDescriptor.

py/selenium/webdriver/common/bidi/storage.py [355]

-partition=PartitionKey(...)
+partition=BrowsingContextPartitionDescriptor(...)
  • Apply / Chat
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly identifies that the example code in the get_cookies docstring uses an incorrect type for the partition parameter, which would mislead users and cause an error.

Low
  • Update

@iampopovich
Copy link
Contributor Author

@cgoldberg sorry , my bad ,i ruined all tests with imported WebElement type in shadowroot class. I think there will be pitfalls with the implementation of type hints in #15697 🥶

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

Labels

B-devtools Includes everything BiDi or Chrome DevTools related B-support Issue or PR related to support classes C-py Python Bindings Review effort 2/5

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants