How to Add Optional Arguments in argparse in Python
Use
parser.add_argument() with a name starting with dashes (e.g., --option) to add optional arguments in argparse. Optional arguments can have default values and are not required when running the script.Syntax
To add an optional argument in argparse, use add_argument() with a name starting with dashes. You can specify a default value, help text, and the type of the argument.
--name: The optional argument name, starting with dashes.help: Description shown in the help message.default: Value used if the argument is not provided.type: The data type of the argument value.
python
parser.add_argument('--option', help='Description', default='default_value', type=str)
Example
This example shows how to add an optional argument --name that prints a greeting. If --name is not given, it uses a default name.
python
import argparse parser = argparse.ArgumentParser(description='Greet the user.') parser.add_argument('--name', help='Name of the user', default='Friend', type=str) args = parser.parse_args() print(f'Hello, {args.name}!')
Output
Hello, Friend!
Common Pitfalls
Common mistakes when adding optional arguments include:
- Using a name without dashes, which makes the argument required instead of optional.
- Not setting a default value, which makes the argument None if not provided.
- Confusing positional and optional arguments.
Here is a wrong and right way:
python
# Wrong: no dashes means required positional argument parser.add_argument('name', help='User name') # Right: dashes make it optional parser.add_argument('--name', help='User name', default='Guest')
Quick Reference
Tips for optional arguments in argparse:
- Start optional argument names with
--or-. - Use
defaultto set a fallback value. - Use
helpto describe the argument for users. - Specify
typeto convert input automatically. - Access the argument value with
args.argument_name.
Key Takeaways
Optional arguments in argparse start with dashes like --option.
Use default to provide a value when the argument is missing.
Always add help text to explain the argument.
Avoid missing dashes to prevent making arguments required.
Access optional arguments via the parsed args object.