I am trying to understand the argparse
package and I really can't find an answer to this very simple question:
-a
and --argument
when adding an argument?Sometimes, I find both in one add_argument()
like here:
parser.add_argument(
"-f", "--file",
help="file path"
)
Rust-like Option and Result types in Python, slotted and fully typed. An Option type represents an optional value, every Option is either Some and contains Some value, or NONE.
Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
Python argparse optional argument The example adds one argument having two options: a short -o and a long --ouput . These are optional arguments. The module is imported. An argument is added with add_argument .
Click actually implements its own parsing of arguments and does not use optparse or argparse following the optparse parsing behavior. The reason it's not based on argparse is that argparse does not allow proper nesting of commands by design and has some deficiencies when it comes to POSIX compliant argument handling.
If both are specified, then argparse will store the value in the long form ('argument') rather than the short form ('a'). It will infer the destination, so "--foo-bar" will be stored in foo_bar
.
You can mash together short forms and use a single hyphen (-af
) but unlike some *NIX commands, order is important: If your argument requires a value (-f filename
) then the argument must appear as the final argument of the group of short-form arguments:
cmd -af my_file # works
cmd -fa my_file # does not work
Compare this with the monster tar(1)
which allows tar -cfC myfile.tar ./directory
and will correctly sort it out as logically equivalent to tar -c -f myfile.tar -C ./directory
. Also, some long forms allow the use of '=' when specifying the option tar -cf myfile.tar
, versus tar -c --file=myfile.tar
. You cannot use '=' on short forms.
Fortunately, python argparse doesn't care about '='. Use it or not, with short form or long form.
# All equivalent:
cmd -af=my_file
cmd -a -f my_file
cmd -a -fmy_file
cmd -afmy_file
cmd --file my_file -a
cmd --file=my_file -a
Does it matter? As another answer suggests, the long form can help with readability. Short form can make your power-users happier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With