Simple argparse example wanted: 1 argument, 3 results
For a quick start, here's a simple argparse
example. An integer argument is processed to provide three distinct outcomes:
Running this script from the command line, like python scriptname.py 4
, it interprets ‘4’ as the ‘num’ input.
Advanced argparse handling techniques
The above script is good for a quick start, but argparse
is a much more powerful beast. Let's delve deeper.
Custom validation of argument values
You may need to validate argument inputs against specific conditions. Here we validate if the provided argument is a positive integer:
Handling different types
Argparse lets you handle different argument types with flexibility. Let's process an integer, list, or string differently:
The ins and outs of argparse
Argparse doesn't stop impressing us with its power and versatility. Let's explore more.
Implicit argument type conversion
Argparse can automatically convert the argument type using the type
parameter of add_argument()
. This saves you from repeatedly writing int(my_argument)
in your code.
Handling boolean flags
American football is not the only place where flags matter. argparse
makes handling boolean flags a breeze with action='store_true'
:
Now args.flag
will give you True
if --flag
is used in the command line, and False
otherwise.
Grouping related arguments
Improve the visual hierarchy and logical grouping of your argument structure, very much like how it's convenient to have all dairy products located in one aisle in your local supermarket:
Troubleshooting and best practices
Named vs positional arguments
Remember: Positional arguments are unnamed but mandatory, while named arguments (starting with -
or --
) are optional.
Enlightening help messages
Help your future self and fellow coders by always defining a useful help
message while adding each argument. Do they know what you were thinking while writing the script? Probably not!
Consistent argument naming
Keeping argument names consistently either snake_case
or camelCase
avoids confusion and keeps your script neat and orderly as a German Innenhof (inner courtyard).
Cooking without burning: test your inputs
Just like in cooking, always taste your dish (test your script) before serving (sharing with others). Catch and handle edge cases, and always display a friendly message for invalid inputs.
Was this article helpful?