44

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?

1

1 Answer 1

55

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")
Sign up to request clarification or add additional context in comments.

5 Comments

Often times, you can easily make a "required" option optional again by assigning a suitable default value to the option.
@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.
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 - I was just following this suggestion. 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.
There is some debate among Python developers about the name 'optional arguments' and whether it can be improved. bugs.python.org/issue9694. There is a long history in the UNIX world of calling arguments with -,-- flags options or optionals.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.