Python argparse case mismatch between optional and positional arguments

I was wondering why there is a mismatch between case conversion of optional and positional arguments in Python argparse

. The addition '--optional-argument'

to the parser will have a name 'optional_argument'

, but the positional argument will remain positional-argument

.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('positional-argument')
parser.add_argument('--optional-argument')
arg_dict = vars(parser.parse_args('Positional --optional-argument Optional'.split()))
print(arg_dict)
# {'positional-argument': 'Positional', 'optional_argument': 'Optional'}

      

I could change the way I add the positional argument to the parser, but the inconsistency will remain (albeit elsewhere)

parser.add_argument('positional_argument')
parser.add_argument('--optional-argument')
# {'positional_argument': 'Positional', 'optional_argument': 'Optional'}

      

+3


source to share


1 answer


It looks like this is a known issue. https://bugs.python.org/issue15125

Possible workarounds:



  • If you are using 'positional-argument'

    , you can retrieve it from the namespace with getattr()

    .

  • If you are using 'positional_argument'

    , you can change how help is displayed in the output with metavar='positional-argument'

    .

+3


source







All Articles