3
votes

I was wondering why the inconsistency between the case-transformation of optional and positional arguments in Python's argparse. Adding the '--optional-argument' to the parser will be named 'optional_argument', but positional argument would stay 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 would remain (though at a different place)

parser.add_argument('positional_argument')
parser.add_argument('--optional-argument')
# {'positional_argument': 'Positional', 'optional_argument': 'Optional'}
1
The dash replacement lets you access the value with args.optional_argument (with a valid Python attribute name). You usually have more freedom in choosing the Positionals dest. And if you use a metavar your user doesn't even see the dest in the help. - hpaulj

1 Answers

3
votes

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

Suggested workarounds:

  • If you use 'positional-argument', you can extract it from the namespace using getattr().

  • If you use 'positional_argument', you can change how it is displayed in the help output with metavar='positional-argument'.