Skip to content

Conversation

@mattwang44
Copy link
Contributor

@mattwang44 mattwang44 commented Sep 5, 2025

(this contribution is made during PyCon TW sprint)

fixes #138525. Here's the output of my local build with this patch.

>>> from argparse import BooleanOptionalAction, ArgumentParser
>>> p = ArgumentParser(prefix_chars='+')
>>> p.add_argument("++foo", action=BooleanOptionalAction)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    p.add_argument("++foo", action=BooleanOptionalAction)
    ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/whw/Desktop/cpython/Lib/argparse.py", line 1554, in add_argument
    action._check_compatibility(self)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
  File "/Users/whw/Desktop/cpython/Lib/argparse.py", line 969, in _check_compatibility
    raise ValueError(f"BooleanOptionalAction requires '-' in prefix_chars.")
ValueError: BooleanOptionalAction requires '-' in prefix_chars.

I believe the description of BooleanOptionalAction on the argparse doc has already implied that it should be used with prefix_chars containing '-', so I didn't make any change to the docs.

@corona10
Copy link
Member

corona10 commented Sep 5, 2025

Would like to add NEWS.d to use blurb tool?

@serhiy-storchaka
Copy link
Member

Isn't it too late? It raises an error when the option is used, not when it is defined.

@mattwang44
Copy link
Contributor Author

mattwang44 commented Sep 7, 2025

Isn't it too late? It raises an error when the option is used, not when it is defined.

I find it difficult to achieve this without changing the interface. I've added a generic _check_compatibility() validation hook in the Action base class that gets called after action creation in add_argument(), allowing BooleanOptionalAction to validate itself against the parser's prefix_chars without leaking action-specific knowledge into _ActionsContainer. PTAL.

@serhiy-storchaka
Copy link
Member

Thank you for your PR, @mattwang44, but after adding support of alternate prefix chars in #138692 this check is no longer needed.

@savannahostrowski
Copy link
Member

Hey @mattwang44! Thanks for opening the original issue and opening a PR!

If you're interested in continuing to contribute to argparse, we have a project board tracking open argparse issues that could use attention. There are issues ranging from small fixes/good first issues to larger enhancements, and I'm happy to help guide you through any of them if you'd like to pick something up.

Thanks again for your contribution, and I hope to see more PRs from you in the future!

@mattwang44 mattwang44 deleted the gh-138525 branch November 23, 2025 03:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

argparse.BooleanOptionalAction silently failed when used with parser whose prefix_chars has no '-'

5 participants