Argparse optional positional arguments?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
To make a positional argument optional in Python's argparse, set nargs='?' when calling add_argument(). This tells the parser to consume zero or one value from the command line. If the user omits the argument, the default value is used. For accepting zero or more values, use nargs='*'. For one or more, use nargs='+'.
How nargs Controls Positional Arguments
By default, positional arguments in argparse are required. The nargs parameter changes how many command-line values the argument consumes, and using ?, *, or + makes the argument flexible.
| nargs Value | Values Consumed | Result Type | Required? | Behavior When Omitted |
| (not set) | Exactly 1 | String | Yes | Error |
'?' | 0 or 1 | String or default | No | Uses default value |
'*' | 0 or more | List | No | Empty list [] |
'+' | 1 or more | List | Yes (at least 1) | Error |
2 (integer) | Exactly 2 | List of 2 | Yes | Error |
The key insight is that nargs='?' returns a single value (string), while nargs='*' and nargs='+' always return a list, even if only one value is provided.
nargs='?' in Detail
nargs='?' is the most common choice for an optional positional argument. It has three states:
- Argument present with a value: the value is used.
- Argument absent: the
defaultvalue is used. - Argument present without a value (only applies to optional flags, not positional): the
constvalue is used.
nargs='*' for Zero or More Values
Use nargs='*' when the user may provide any number of values, including none at all. The result is always a list.
nargs='+' for One or More Values
Use nargs='+' when at least one value is required, but additional values are welcome. This is useful for commands that operate on one or more files.
Mixing Required and Optional Positional Arguments
A common pattern is one required positional argument followed by an optional one. Order matters: argparse processes positional arguments left to right.
Using const with Optional Flag Arguments
The const parameter becomes relevant when nargs='?' is used with optional (flag) arguments rather than positional ones. It provides a value when the flag is present but no value follows it.
This three-state behavior (absent / present without value / present with value) is powerful for flags where you want a sensible default but allow override.
Type Conversion with Optional Arguments
The type parameter works with optional positional arguments just like required ones. The conversion is applied to the command-line value, not to the default.
A Complete CLI Example
Here is a realistic command-line tool that combines required arguments, optional positional arguments, and optional flags:
Comparison with click and typer
argparse is part of the standard library, but third-party libraries like click and typer offer different approaches to optional arguments:
| Feature | argparse | click | typer |
| Standard library | Yes | No (pip install) | No (pip install) |
| Optional positional | nargs='?' | click.Argument(required=False) | typer.Argument(default=...) |
| Type validation | type=int | type=int | Python type hints |
| Help generation | Automatic | Automatic | Automatic |
| Subcommands | add_subparsers() | @group.command() | app.command() |
| Learning curve | Medium | Low | Low |
For simple scripts and standard-library-only requirements, argparse is the right choice. For larger CLI applications, click or typer reduce boilerplate.
Common Pitfalls
Putting an optional positional before a required one. Argparse processes positional arguments left to right. If an optional nargs='?' argument appears before a required one, the parser may consume the required argument's value for the optional slot, leaving the required argument unsatisfied.
Always place required positional arguments before optional ones.
Expecting a string from nargs='*'. nargs='*' always returns a list, even if only one value is provided. If your code expects a string, you will get a TypeError when concatenating or comparing.
Forgetting that default is not type-converted. The type function is applied only to command-line input, not to the default value. If you set type=int and default="3", the default will be the string "3", not the integer 3.
Using nargs='?' when nargs='*' is intended. nargs='?' accepts zero or one value. If the user might pass multiple values, use nargs='*' or nargs='+' instead.
Not providing help text. Argparse auto-generates usage and help output. Without help strings, --help output is cryptic and unhelpful to users.
Summary
- Set
nargs='?'to make a positional argument optional. The user can provide zero or one value. - Set
nargs='*'for zero or more values (returns a list) andnargs='+'for one or more values (also a list, but errors if none provided). - Always provide a
defaultvalue for optional positional arguments. Without it, the default isNone. - Place required positional arguments before optional ones to avoid ambiguous parsing.
- Use the
constparameter withnargs='?'on optional flag arguments for three-state behavior (absent, present without value, present with value). - The
typefunction applies only to command-line input, not to thedefaultvalue. Make sure the default is already the correct type. - For larger CLI applications, consider
clickortyperas alternatives that reduce argument-handling boilerplate.
Related reading
- Argparse optional positional arguments?
- Argparse Required arguments listed under optional arguments?
- Argparse Way to include default values in '--help'?
- ARIMA Forecast Cannot cast ufunc subtract output from dtype'float64' to dtype'int64' with casting rule 'same_kind
- as_list is not defined on an unknown TensorShape
- Asking for examples of async generators not directly transformable into manually implemented async iteration
- assertEquals vs. assertEqual in python
- AssertionError Could not compute output Tensor
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.