Skip to content

Update argparse to 3.13.5 #5874

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 30, 2025
Merged

Conversation

ShaharNaveh
Copy link
Contributor

@ShaharNaveh ShaharNaveh commented Jun 30, 2025

Summary by CodeRabbit

  • New Features

    • Added support for marking arguments, options, and subcommands as deprecated, with warnings shown when used.
    • Introduced parsing modes that allow positional and optional arguments to be intermixed.
    • Improved internationalization of help messages and usage formatting.
    • Enhanced error handling with more consistent and informative error messages.
  • Bug Fixes

    • Improved handling of ambiguous option strings and error reporting.
    • Fixed help message formatting inconsistencies and improved display of choices.
  • Tests

    • Expanded test coverage for deprecated arguments, intermixed parsing, error handling, and new features.
    • Added tests for new argument actions, help formatting, and edge cases.

Copy link

coderabbitai bot commented Jun 30, 2025

Walkthrough

The changes introduce significant enhancements and refactoring to the argparse module and its test suite. Key updates include support for deprecation warnings on arguments and subparsers, improved internationalization, more flexible argument parsing (including intermixed positional and optional arguments), better error handling, and expanded test coverage for new and edge-case behaviors.

Changes

File(s) Change Summary
Lib/argparse.py Refactored help formatting for i18n, added deprecation support for arguments/subparsers, improved parsing logic for intermixed arguments, enhanced error handling, and introduced new/modified public and internal methods and attributes.
Lib/test/test_argparse.py Expanded and improved test suite: added new test classes for deprecation, intermixed parsing, StrEnum choices, extend/append actions, error handling, and help formatting; increased coverage for new features and edge cases.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ArgumentParser
    participant Action
    participant Warnings

    User->>ArgumentParser: parse_args(args)
    ArgumentParser->>ArgumentParser: _parse_known_args2(args, namespace, intermixed)
    ArgumentParser->>Action: Check if action is deprecated
    alt Deprecated action
        ArgumentParser->>Warnings: Issue deprecation warning
    end
    ArgumentParser->>ArgumentParser: Parse arguments (intermixed or standard)
    ArgumentParser->>Action: Execute action for argument
    ArgumentParser->>User: Return namespace
Loading
sequenceDiagram
    participant User
    participant ArgumentParser
    participant SubParsersAction
    participant Warnings

    User->>ArgumentParser: add_subparsers()
    ArgumentParser->>SubParsersAction: add_parser(name, deprecated=True)
    User->>ArgumentParser: parse_args([subcommand, ...])
    ArgumentParser->>SubParsersAction: __call__(...)
    alt Deprecated subparser
        SubParsersAction->>Warnings: Issue deprecation warning
    end
    SubParsersAction->>User: Return namespace
Loading

Poem

In the garden of code where arguments grow,
Now warnings for old seeds gently flow.
Options and positions can intermingle with glee,
While deprecated paths buzz like a bee.
Tests now hop farther, with coverage so wide—
A rabbit’s delight, with carrots of pride! 🥕

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (1)
Lib/argparse.py (1)

878-883: Avoid using private warnings API.

The code uses warnings._deprecated, which is a private function. Private APIs are not guaranteed to be stable across Python versions.

-                import warnings
-                warnings._deprecated(
-                    field_name,
-                    "{name!r} is deprecated as of Python 3.12 and will be "
-                    "removed in Python {remove}.",
-                    remove=(3, 14))
+                import warnings
+                warnings.warn(
+                    f"{field_name!r} is deprecated as of Python 3.12 and will be "
+                    f"removed in Python 3.14.",
+                    DeprecationWarning,
+                    stacklevel=2)
🧹 Nitpick comments (2)
Lib/argparse.py (2)

227-228: Consider using dict literal syntax for better readability.

The static analysis tool correctly identifies that a dict literal would be more Pythonic here.

-                heading_text = _('%(heading)s:') % dict(heading=self.heading)
+                heading_text = _('%(heading)s:') % {'heading': self.heading}

389-473: Complex but necessary refactoring of usage formatting logic.

The extraction of _get_actions_usage_parts improves separation of concerns. While static analysis flags high complexity (20 local variables, 21 branches), this appears justified given the intricate logic for handling mutually exclusive groups with proper bracket placement and separator insertion.

Consider adding inline comments to explain the group formatting logic, particularly around lines 457-470 where separators are inserted.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d5d3507 and 8de3eac.

📒 Files selected for processing (2)
  • Lib/argparse.py (70 hunks)
  • Lib/test/test_argparse.py (46 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
`**/*.py`: Follow PEP 8 style for custom Python code Use ruff for linting Python code

**/*.py: Follow PEP 8 style for custom Python code
Use ruff for linting Python code

📄 Source: CodeRabbit Inference Engine (.github/copilot-instructions.md)

List of files the instruction was applied to:

  • Lib/test/test_argparse.py
  • Lib/argparse.py
`Lib/**/*.py`: Minimize modifications to CPython standard library files in the `Lib/` directory

Lib/**/*.py: Minimize modifications to CPython standard library files in the Lib/ directory

📄 Source: CodeRabbit Inference Engine (.github/copilot-instructions.md)

List of files the instruction was applied to:

  • Lib/test/test_argparse.py
  • Lib/argparse.py
`Lib/test/**/*.py`: NEVER comment out or delete any test code lines except for r...

Lib/test/**/*.py: NEVER comment out or delete any test code lines except for removing @unittest.expectedFailure decorators and upper TODO comments in test files
NEVER modify test assertions, test logic, or test data in test files
When a test cannot pass due to missing language features, keep it as expectedFailure and document the reason
The only acceptable modifications to test files are: 1. Removing @unittest.expectedFailure decorators and the upper TODO comments when tests actually pass 2. Adding @unittest.expectedFailure decorators when tests cannot be fixed
Add a # TODO: RUSTPYTHON comment when modifications are made to tests in Lib/test
Use unittest.skip("TODO: RustPython <reason>") or unittest.expectedFailure with # TODO: RUSTPYTHON <reason> comment in test files when skipping or marking expected failures

📄 Source: CodeRabbit Inference Engine (.github/copilot-instructions.md)

List of files the instruction was applied to:

  • Lib/test/test_argparse.py
🧠 Learnings (1)
Lib/test/test_argparse.py (1)

undefined

<retrieved_learning>
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to Lib/test/**/*.py : The only acceptable modifications to test files are: 1. Removing @unittest.expectedFailure decorators and the upper TODO comments when tests actually pass 2. Adding @unittest.expectedFailure decorators when tests cannot be fixed
</retrieved_learning>

🪛 Pylint (3.3.7)
Lib/test/test_argparse.py

[refactor] 2262-2262: Too few public methods (1/2)

(R0903)


[refactor] 2328-2328: Consider using '{"description": '2 description'}' instead of a call to 'dict'.

(R1735)


[refactor] 2400-2400: Too few public methods (0/2)

(R0903)


[error] 2406-2406: Class 'C' has no 'foo' member

(E1101)


[error] 2407-2407: Class 'C' has no 'bar' member

(E1101)


[error] 2408-2408: Class 'C' has no 'w' member

(E1101)


[error] 2409-2409: Class 'C' has no 'x' member

(E1101)


[refactor] 5403-5403: Consider using '{"type": int}' instead of a call to 'dict'.

(R1735)


[refactor] 5403-5403: Consider using '{"nargs": '+'}' instead of a call to 'dict'.

(R1735)


[refactor] 5404-5404: Consider using '{"choices": ['a', 'b']}' instead of a call to 'dict'.

(R1735)


[error] 5896-5896: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 5902-5902: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 5908-5908: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 5915-5915: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 5925-5925: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 5931-5931: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 5937-5937: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 5943-5943: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 5955-5955: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 5960-5960: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 5966-5966: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 5977-5977: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 5982-5982: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 5988-5988: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 6000-6000: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 6005-6005: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)


[error] 6011-6011: Instance of 'TextIOWrapper' has no 'getvalue' member

(E1101)

Lib/argparse.py

[refactor] 227-227: Consider using '{"heading": self.heading}' instead of a call to 'dict'.

(R1735)


[refactor] 389-389: Too many local variables (20/15)

(R0914)


[refactor] 389-389: Too many branches (21/12)

(R0912)


[refactor] 389-389: Too many statements (51/50)

(R0915)


[refactor] 539-547: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it

(R1705)


[refactor] 709-714: Unnecessary "elif" after "return", remove the leading "el" from "elif"

(R1705)


[refactor] 961-961: Consider using Python 3 style super() without arguments

(R1725)


[refactor] 984-984: Consider using Python 3 style super() without arguments

(R1725)


[refactor] 1003-1003: Consider using Python 3 style super() without arguments

(R1725)


[refactor] 1091-1091: Consider using Python 3 style super() without arguments

(R1725)


[refactor] 1115-1115: Consider using Python 3 style super() without arguments

(R1725)


[refactor] 1910-1910: Too many branches (13/12)

(R0912)


[refactor] 1948-1948: Too many local variables (38/15)

(R0914)


[refactor] 1948-1948: Too many branches (33/12)

(R0912)


[refactor] 1948-1948: Too many statements (168/50)

(R0915)


[refactor] 2381-2381: Redefining argument with the local name 'option_string'

(R1704)


[refactor] 2397-2397: Redefining argument with the local name 'option_string'

(R1704)


[refactor] 2492-2492: Too many branches (13/12)

(R0912)

🪛 Flake8 (7.2.0)
Lib/test/test_argparse.py

[error] 2992-2992: continuation line under-indented for visual indent

(E128)


[error] 5427-5427: continuation line under-indented for visual indent

(E128)


[error] 5429-5429: continuation line under-indented for visual indent

(E128)


[error] 6123-6123: continuation line under-indented for visual indent

(E128)


[error] 6124-6124: continuation line under-indented for visual indent

(E128)


[error] 6128-6128: continuation line under-indented for visual indent

(E128)


[error] 6129-6129: continuation line under-indented for visual indent

(E128)


[error] 6223-6223: continuation line under-indented for visual indent

(E128)


[error] 6224-6224: continuation line under-indented for visual indent

(E128)


[error] 6237-6237: continuation line under-indented for visual indent

(E128)


[error] 6238-6238: continuation line under-indented for visual indent

(E128)


[error] 6309-6309: continuation line under-indented for visual indent

(E128)


[error] 6310-6310: continuation line under-indented for visual indent

(E128)


[error] 6325-6325: continuation line under-indented for visual indent

(E128)


[error] 6326-6326: continuation line under-indented for visual indent

(E128)


[error] 6328-6328: continuation line under-indented for visual indent

(E128)


[error] 6329-6329: continuation line under-indented for visual indent

(E128)


[error] 6331-6331: continuation line under-indented for visual indent

(E128)


[error] 6332-6332: continuation line under-indented for visual indent

(E128)


[error] 6738-6738: continuation line under-indented for visual indent

(E128)


[error] 6739-6739: continuation line under-indented for visual indent

(E128)


[error] 6741-6741: continuation line under-indented for visual indent

(E128)


[error] 6742-6742: continuation line under-indented for visual indent

(E128)


[error] 6744-6744: continuation line under-indented for visual indent

(E128)


[error] 6745-6745: continuation line under-indented for visual indent

(E128)


[error] 6747-6747: continuation line under-indented for visual indent

(E128)


[error] 6748-6748: continuation line under-indented for visual indent

(E128)

Lib/argparse.py

[error] 2023-2023: continuation line under-indented for visual indent

(E128)


[error] 2318-2318: visually indented line with same indent as next logical line

(E129)

⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run tests under miri
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Ensure compilation on various targets
🔇 Additional comments (16)
Lib/test/test_argparse.py (9)

18-21: LGTM!

The new imports are appropriate for the added test functionality.


286-289: Good use of subTest for better test diagnostics

Adding subTest context managers improves test failure reporting by clearly identifying which specific test case failed.

Also applies to: 295-297


1027-1054: Well-structured test coverage for StrEnum support

The test class properly covers parsing enum values, help message formatting, and error handling for invalid enum values.


1497-1508: Good test coverage for the new 'extend' action

The test properly validates the extend action behavior with positional arguments.


2399-2410: LGTM! Test for class namespace parsing

The test correctly validates parsing arguments into a class namespace. The static analysis warnings about missing members are false positives since attributes are dynamically set during parsing.


5884-6014: Comprehensive test coverage for deprecated arguments feature

Excellent implementation covering all deprecation scenarios including options, boolean options, positional arguments, varargs, and subparsers. The use of captured_stderr() to verify warning messages is appropriate.


6114-6241: Thorough test coverage for double-dash handling

Excellent coverage of double-dash separator behavior across different argument configurations including single/multiple arguments, subparsers, and remainder arguments.


6750-6757: Correct handling of expectedFailure test

The test is properly marked with @unittest.expectedFailure and includes the required # TODO: RUSTPYTHON comment as per the coding guidelines.


6762-6767: Good addition of translation testing support

The TestTranslations class and the snapshot update mechanism in the main block properly support internationalization testing.

Also applies to: 6775-6779

Lib/argparse.py (7)

813-814: Well-implemented deprecation support across all action classes.

The addition of the deprecated parameter is consistently implemented across all Action subclasses, providing a clean API for marking deprecated arguments. This will enable better user guidance when migrating code.

Also applies to: 825-825, 839-839, 862-863, 901-902, 925-926, 943-944, 959-960, 982-983, 988-988, 1001-1002, 1009-1010, 1025-1026, 1043-1044, 1062-1063, 1072-1073, 1089-1090, 1097-1098, 1113-1114, 1120-1121, 1135-1136


1182-1182: Clean implementation of subparser deprecation support.

The use of a set to track deprecated subparser names and the warning mechanism during parsing provides a good user experience for deprecated subcommands.

Also applies to: 1193-1193, 1221-1224, 1247-1250


1900-1905: Excellent improvement to error handling with exit_on_error support.

The consistent replacement of direct error() calls with ArgumentError exceptions when exit_on_error=False makes the parser more flexible for programmatic use. This is a valuable enhancement for applications that need to handle parsing errors without terminating.

Also applies to: 2234-2234, 2250-2250, 2277-2277, 2463-2468


1908-1910: Well-designed implementation of intermixed argument parsing.

The new intermixed parsing feature is cleanly implemented with appropriate safety checks (preventing usage with PARSER/REMAINDER nargs). The separation into _parse_known_args2 method with an intermixed parameter maintains backward compatibility while adding the new functionality.

Also applies to: 1948-1948, 2190-2213, 2460-2487


2414-2452: Improved nargs pattern generation with better handling of '--' separator.

The distinction between patterns for optional vs positional arguments provides more accurate parsing, especially for edge cases involving the '--' separator. The patterns correctly handle the different semantics of '--' in various contexts.


2570-2579: Smart enhancement to choices validation.

The ability to use a string as choices (e.g., choices='abc' to allow 'a', 'b', or 'c') is a nice usability improvement. The implementation correctly converts the string to an iterator for the membership test.


2659-2663: Good addition of dedicated warning method.

The _warning method provides consistent formatting for warning messages, following the same pattern as the existing error method. This improves maintainability and user experience.

Copy link
Member

@youknowone youknowone left a comment

Choose a reason for hiding this comment

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

👍

@youknowone youknowone merged commit 01117f4 into RustPython:main Jun 30, 2025
12 checks passed
@ShaharNaveh ShaharNaveh deleted the update-argparse branch June 30, 2025 21:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants