Python argparse optional positional arguments with nargs='?'
Codemia Knowledge Hub ·
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
Positional arguments in argparse are required by default. The nargs parameter changes how many command-line values the argument consumes.
| 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 |
Note that nargs='?' returns a single value (string), while nargs='*' and nargs='+' always return a list, even if only one value is provided.
nargs='?': zero or one value
nargs='?' is the usual 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 pass any number of values, including none. The result is always a list.
nargs='+' for one or more values
Use nargs='+' when at least one value is required and more are allowed, for example commands that operate on one or more files.
A required positional followed by an optional one
A common pattern is one required positional argument followed by an optional one. Order matters because argparse processes positional arguments left to right.
const with optional flag arguments
const matters when nargs='?' is used on an optional flag rather than a positional argument. It supplies a value when the flag is present but no value follows it.
This three-state behavior (absent, present without value, present with value) suits flags that need a sensible default but allow an override.
Type conversion with optional arguments
type works on optional positional arguments just as on required ones. The conversion is applied to the command-line value and to a default given as a string; a non-string default is used as-is.
Complete example: a CSV to JSON converter
This tool combines a required argument, an optional positional argument and an optional flag:
Optional arguments in click and typer
argparse is in the standard library. The third-party libraries click and typer handle optional arguments differently:
| 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.
Mistakes with optional positional arguments
Putting an optional positional before a required one. Argparse matches positional arguments left to right, giving the required one priority. With one value the optional slot keeps its default; with two, the first value fills the optional slot. The usage line reads [output] input, which confuses users.
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. Code that expects a string gets a TypeError when concatenating or comparing.
Expecting a non-string default to be type-converted. type is applied to a default only when the default is a string. default="3" with type=int gives the integer 3, but default=3.5 with type=int stays the float 3.5.
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 generates usage and help output automatically. Without help strings, --help output is cryptic.
Omitting default. Without a default, an omitted optional positional argument is None.
Related reading
- 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
- AssertionError Some objects had attributes which were not restored
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.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 courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.