0

This is a program that already exists and I'm trying to extend it - so my hands are tied somewhat :-(.

I have a program where I want to add an option that takes an unknown number of values so I'm trying to use nargs='+'. I can spot when a value is not actually for my option and is a positional argument and I can then use setattr to set the positional argument - but argparse doesn't get a chance to find the positional argument itself so complains.

The syntax for the command, as show in arparse generated help text, is

command [--option value [value...]] positional

In theory this is possible if I did this instead

command positional [--option value [value...]]

This is precisely how examples, even in the argparse documentation, work but that is NOT how the command is currently used, NOT how users typically provide programs with options and NOT how argparse generated help text shows the expected syntax.

So it there a way to somehow both handle the positional but also tell argparse 'oh, I found this positional so no need to complain that it is missing'?

Paul D Smith
  • 639
  • 5
  • 16
  • So you have a `+` optional followed by a required positional. Due to the way parsing alternates between optionals and positionals, `--option` grabs all strings, and leaves nothing for the positional. It's been discussed in Python bug/issues, but isn't a trivial fix. `--option` needs some sort of 'end of list' marker, such as another optional. `--` might also work. – hpaulj Apr 12 '18 at 17:21
  • The generated `help` displays the positionals after all the optionals, regardless of how they defined. But parsing is intended to be order independent - except for glitches like this. – hpaulj Apr 12 '18 at 18:08
  • 1
    See [Argparse - do not catch positional arguments with `nargs`.](https://stackoverflow.com/questions/26985650/argparse-do-not-catch-positional-arguments-with-nargs) for more details. – hpaulj Apr 12 '18 at 18:17
  • Thanks - I had considered the 'append' option but I like the idea of using '--' to end the parsing even better. My personal 'idealish' solution would be to allow the action to either have the action report how many arguments it took (it can detect 'this ain't an integer' for example) or allow the custom type parser to similarly return 'here's your value' or None indicating 'this value would work here - clearly not for this option'. Unfortunately neither solution is back-compatible. – Paul D Smith Apr 16 '18 at 07:44

0 Answers0