41

Python's argparse module has what are called 'optional' arguments. All arguments whose name starts with - or -- are optional by default. Typically, compulsory arguments are positional, and hence when running the program, they are not explicitly named.

For example, in a script which had:

parser.add_argument('language', help="Output language")

Invocations would look like:

$ hello-world czech

It may sometimes be nicer to have a compulsory argument passed by name (e.g. scripted invocations are easier to read this way), but still be compulsory. i.e.

$ hello-world --use-lang czech

How to achieve this? Named arguments are called 'optional' in the argparse documentation, which makes it sound like they cannot be compulsory. Is there a way to make them compulsory?

ArjunShankar
  • 23,020
  • 5
  • 61
  • 83

1 Answers1

53

According to canonical documentation, it is possible to declare 'optional' arguments that are compulsory. You use the required named argument of add_argument:

parser.add_argument('--use-lang', required=True, help="Output language")
ArjunShankar
  • 23,020
  • 5
  • 61
  • 83
  • 1
    Often times, you can easily make a "required" option optional again by assigning a suitable default value to the option. – chepner Mar 11 '14 at 18:39
  • 7
    @user2864740 - I just wanted to document this because I had to spend some time reading the official docs before figuring it out. I don't blog, and anyway, SO is a much better forum than a private blog. I often search SO before asking google. – ArjunShankar Mar 11 '14 at 18:45
  • The documentation *already* documents this; reading documentation/API is a developer's responsibility. Again, I'm not against self-answering, but *give the community time*. (Or go start a blog, which is a great way to write/vent/re-document these sort of things!) – user2864740 Mar 11 '14 at 18:50
  • 1
    @user2864740 - I was just following [this suggestion](http://meta.stackexchange.com/a/17847/179533). The answer is now a community wiki. Unfortunately, seems I cannot turn the question into one now. If you think this isn't a great question because it is already documented, you might want to downvote the question. I have no problem deleting substandard questions. – ArjunShankar Mar 11 '14 at 18:55
  • 1
    There is some debate among Python developers about the name 'optional arguments' and whether it can be improved. http://bugs.python.org/issue9694. There is a long history in the UNIX world of calling arguments with `-,--` flags `options` or `optionals`. – hpaulj Mar 12 '14 at 22:25