Skip to content

Commit c14013f

Browse files
committed
add action method for parser compatibility check
1 parent 2932858 commit c14013f

File tree

2 files changed

+14
-9
lines changed

2 files changed

+14
-9
lines changed

Lib/argparse.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -922,6 +922,10 @@ def format_usage(self):
922922
def __call__(self, parser, namespace, values, option_string=None):
923923
raise NotImplementedError('.__call__() not defined')
924924

925+
def _check_compatibility(self, container):
926+
"""Check whether the action is compatible with the container."""
927+
pass
928+
925929

926930
class BooleanOptionalAction(Action):
927931
def __init__(self,
@@ -954,15 +958,16 @@ def __init__(self,
954958

955959

956960
def __call__(self, parser, namespace, values, option_string=None):
957-
if '-' not in parser.prefix_chars:
958-
raise ValueError("BooleanOptionalAction requires '-' in parser's prefix_chars")
959-
960961
if option_string in self.option_strings:
961962
setattr(namespace, self.dest, not option_string.startswith('--no-'))
962963

963964
def format_usage(self):
964965
return ' | '.join(self.option_strings)
965966

967+
def _check_compatibility(self, container):
968+
if '-' not in container.prefix_chars:
969+
raise ValueError(f"BooleanOptionalAction requires '-' in prefix_chars.")
970+
966971

967972
class _StoreAction(Action):
968973

@@ -1545,6 +1550,9 @@ def add_argument(self, *args, **kwargs):
15451550
if not action.option_strings and action.nargs == 0:
15461551
raise ValueError(f'action {action_name!r} is not valid for positional arguments')
15471552

1553+
# raise an error if the action is not compatible with the parser
1554+
action._check_compatibility(self)
1555+
15481556
# raise an error if the action type is not callable
15491557
type_func = self._registry_get('type', action.type, action.type)
15501558
if not callable(type_func):

Lib/test/test_argparse.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -797,13 +797,10 @@ def test_invalid_name(self):
797797

798798
def test_prefix_chars_incompatibility(self):
799799
parser = argparse.ArgumentParser(prefix_chars='+')
800-
parser.add_argument('++foo', action=argparse.BooleanOptionalAction)
801-
802800
with self.assertRaises(ValueError) as cm:
803-
parser.parse_args(['++foo'])
804-
805-
self.assertIn(str(cm.exception),
806-
"BooleanOptionalAction requires '-' in parser's prefix_chars")
801+
parser.add_argument('++foo', action=argparse.BooleanOptionalAction)
802+
self.assertEqual(str(cm.exception),
803+
"BooleanOptionalAction requires '-' in prefix_chars.")
807804

808805
class TestBooleanOptionalActionRequired(ParserTestCase):
809806
"""Tests BooleanOptionalAction required"""

0 commit comments

Comments
 (0)