DEV Community

Erry Kostala
Erry Kostala

Posted on

Python argparse cheat sheet

I have a confession to make: I never remember how to use argparse. Maybe it’s because I don’t use it often enough to have how it works memorized, but I certainly use it often enough that I’m annoyed every time I have to look it up. Argparse? More like ARGHparse. Either way, I thought I would make a handy cheat sheet that can be quickly looked up rather than reading the documentation.

Read a single argument with a value

parser.add_argument('--id', type=int, nargs=1)

Read a single argument with a default

parser.add_argument('--id', type=int, nargs='?', default=0)

Read a flag (boolean) argument

parser.add_argument('--delete', nargs='?', const=True, default=False)

Read multiple arguments

parser.add_argument('--ids', type=int, nargs='+')

Required arguments

parser.add_argument('--id', type=int, nargs=1, required=True)

That should cover the common use cases, hope this has been helpful for someone other than me!

Top comments (1)

Collapse
 
davedavemckay profile image
David McKay

I like the use of nargs=1 which will mean your script always deals with lists and keep the code consistent, rather than leaving it out and having some lists and some strings or ints.
nargs='?' and nargs='+' are new to me so thanks for them! I use nargs='*' a lot...