DEV Community

Erry Kostala
Erry Kostala

Posted on

2 2

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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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...

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs