Table of Contents#
- Understanding 'arg=val' vs. Standard argparse Formats
- Why argparse Doesn’t Natively Support 'arg=val'
- Parsing 'arg=val' with argparse: Custom Actions
- Step-by-Step Example: Basic 'arg=val' Parsing
- Extracting Values and Handling Edge Cases
- Advanced Tips: Validation, Type Conversion, and Dictionaries
- Alternative: Parsing 'arg=val' with sys.argv (When to Avoid argparse)
- Conclusion
- References
1. Understanding 'arg=val' vs. Standard argparse Formats#
Before diving into solutions, let’s clarify the difference between arg=val and standard argparse formats:
| Format | Example | Use Case |
|---|---|---|
| Standard (flag-based) | --name John --age 30 | Explicit, human-readable flags (common in CLI tools). |
| arg=val | name=John age=30 | Compact key-value pairs (common in configs, scripts, or legacy tools). |
argparse excels at the flag-based format, but arg=val is often preferred for brevity or compatibility with other systems (e.g., CI/CD pipelines, custom scripts).
2. Why argparse Doesn’t Natively Support 'arg=val'#
argparse is designed to parse positional arguments (e.g., script.py input.txt) and optional flags (e.g., --output output.txt). When you pass arg=val to argparse without customization, it treats the entire string (e.g., name=John) as a single positional argument, not a key-value pair. For example:
python script.py name=John age=30By default, argparse would see name=John and age=30 as two separate positional arguments, not as name: John and age: 30. To fix this, we need to teach argparse to split arg=val strings into keys and values.
3. Parsing 'arg=val' with argparse: Custom Actions#
The key to parsing arg=val with argparse is to use custom actions. argparse allows you to define custom behavior for processing arguments via the action parameter in add_argument(). We’ll create a custom action that splits arg=val strings into key-value pairs and stores them in the argparse.Namespace object (the result of parser.parse_args()).
How Custom Actions Work#
An argparse.Action subclass overrides the __call__ method, which is invoked when the argument is parsed. For arg=val parsing, our custom action will:
- Take a list of
arg=valstrings (e.g.,["name=John", "age=30"]). - Split each string into a key (before
=) and value (after=). - Validate that the
=separator exists (to avoid invalid inputs likenameJohn). - Store the key-value pairs in the
Namespace(e.g.,args.name = "John").
4. Step-by-Step Example: Basic 'arg=val' Parsing#
Let’s build a script that parses arg=val arguments using a custom action. We’ll start with a minimal example and expand it.
Step 1: Define the Custom Action#
Create a class inheriting from argparse.Action and override the __call__ method:
import argparse
class KeyValueAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
"""Process list of 'arg=val' strings into key-value pairs."""
for val_str in values:
# Split on the FIRST '=' to handle values with '=' (e.g., "desc=Hello=World")
key, sep, val = val_str.partition('=')
if not sep: # No '=' found
parser.error(f"Invalid 'arg=val' format: '{val_str}'. Use 'key=value'.")
# Store the key-value pair in the namespace (e.g., args.name = "John")
setattr(namespace, key, val)Step 2: Add the Action to argparse#
Use add_argument() to define a positional argument that accepts a list of arg=val strings (via nargs='*') and uses our KeyValueAction:
def main():
parser = argparse.ArgumentParser(
description="Parse 'arg=val' command-line arguments with argparse.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
# Add a positional argument to capture all 'arg=val' pairs
parser.add_argument(
'params', # Name of the argument (used in help text)
nargs='*', # Accept 0 or more 'arg=val' strings
action=KeyValueAction, # Use our custom action
help="Key-value pairs in 'arg=val' format (e.g., name=John age=30)"
)
# Parse the arguments
args = parser.parse_args()
# Extract values (now stored as attributes of args)
print("Parsed values:")
print(f"Name: {getattr(args, 'name', 'Not provided')}") # Use getattr to avoid AttributeError
print(f"Age: {getattr(args, 'age', 'Not provided')}")
if __name__ == "__main__":
main()Step 3: Test the Script#
Run the script with arg=val arguments:
python script.py name=John age=30Output:
Parsed values:
Name: John
Age: 30
If you run it with an invalid format (e.g., nameJohn), argparse will throw an error:
python script.py nameJohn
# Error: argument params: Invalid 'arg=val' format: 'nameJohn'. Use 'key=value'.5. Extracting Values and Handling Edge Cases#
Now that we can parse arg=val arguments, let’s cover how to extract values reliably and handle common edge cases.
Extracting Values#
Values are stored as attributes of the args object (from parser.parse_args()). Use:
- Direct access:
args.name(raisesAttributeErrorif the key is missing). - Safe access:
getattr(args, 'name', default)(avoids errors for missing keys).
Example:
# Safe extraction with defaults
name = getattr(args, 'name', 'Guest')
age = int(getattr(args, 'age', 18)) # Default to 18 if age is missingEdge Cases to Handle#
1. Missing '=' Separator#
The custom action already checks for sep == '' and errors out (via parser.error()), preventing invalid inputs like nameJohn.
2. Values Containing '='#
If a value includes = (e.g., desc=Hello=World), partition('=') splits on the first =, so key=desc, val=Hello=World. This is correct for most use cases.
3. Duplicate Keys#
If a key is passed multiple times (e.g., name=John name=Jane), the last occurrence overwrites previous values (consistent with CLI conventions):
python script.py name=John name=Jane
# Parsed values: Name: Jane4. Required 'arg=val' Pairs#
To enforce required keys (e.g., name must be provided), add validation after parsing:
args = parser.parse_args()
if not hasattr(args, 'name'):
parser.error("Missing required argument: 'name=val' (e.g., name=John)")6. Advanced Tips: Validation, Type Conversion, and Dictionaries#
Restrict Allowed Keys#
To prevent users from passing arbitrary keys (e.g., only allow name, age, city), modify the KeyValueAction to check keys against a whitelist:
class RestrictedKeyValueAction(argparse.Action):
def __init__(self, allowed_keys, *args, **kwargs):
self.allowed_keys = allowed_keys
super().__init__(*args, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
for val_str in values:
key, sep, val = val_str.partition('=')
if not sep:
parser.error(f"Invalid format: '{val_str}'. Use 'key=value'.")
if key not in self.allowed_keys:
parser.error(f"Invalid key '{key}'. Allowed keys: {self.allowed_keys}")
setattr(namespace, key, val)
# Usage in add_argument():
parser.add_argument(
'params',
nargs='*',
action=RestrictedKeyValueAction,
allowed_keys=['name', 'age', 'city'], # Whitelist allowed keys
help="Allowed keys: name, age, city (e.g., name=John age=30)"
)Type Conversion#
By default, values are stored as strings. Convert them to int, bool, or other types after parsing:
# Convert age to int
age = int(getattr(args, 'age', 0))
# Convert 'is_student=True' to a boolean
is_student = getattr(args, 'is_student', 'False').lower() == 'true'Collect Key-Value Pairs into a Dictionary#
For easier access, store all arg=val pairs in a single dictionary instead of individual attributes. Modify the KeyValueAction to populate a dict in the Namespace:
class DictKeyValueAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
# Initialize a dictionary if it doesn't exist
if not hasattr(namespace, self.dest):
setattr(namespace, self.dest, {})
# Populate the dictionary with key-value pairs
for val_str in values:
key, sep, val = val_str.partition('=')
if not sep:
parser.error(f"Invalid 'arg=val' format: '{val_str}'")
getattr(namespace, self.dest)[key] = val
# Usage:
parser.add_argument(
'params',
nargs='*',
action=DictKeyValueAction,
dest='kwargs', # Store pairs in args.kwargs (a dict)
help="Key-value pairs (e.g., name=John age=30)"
)
# Access via dictionary:
args = parser.parse_args()
print(args.kwargs) # {'name': 'John', 'age': '30'}
print(args.kwargs.get('name')) # 'John'7. Alternative: Parsing 'arg=val' with sys.argv (When to Avoid argparse)#
If you don’t need argparse’s features (help messages, validation, flags), you can parse arg=val directly with sys.argv (Python’s list of command-line arguments). This is simpler but lacks argparse’s robustness.
Example with sys.argv:
import sys
def parse_argval():
kwargs = {}
for arg in sys.argv[1:]: # Skip script name (sys.argv[0])
key, sep, val = arg.partition('=')
if not sep:
raise ValueError(f"Invalid 'arg=val' format: {arg}")
kwargs[key] = val
return kwargs
# Usage:
try:
params = parse_argval()
print(params) # {'name': 'John', 'age': '30'}
except ValueError as e:
print(f"Error: {e}")
sys.exit(1)When to use this: Small scripts with no need for help messages, flag-based arguments, or strict validation.
8. Conclusion#
Parsing arg=val arguments with argparse requires a custom action, but it unlocks argparse’s strengths: help messages, validation, and compatibility with other argument types. Here’s a recap:
- Custom Actions: Use
argparse.Actionsubclasses to splitarg=valstrings into key-value pairs. - Edge Cases: Handle missing
=, duplicates, and required keys with validation. - Advanced Features: Restrict allowed keys, convert types, or collect pairs into a dictionary.
- Alternatives: Use
sys.argvfor simple cases, but preferargparsefor robustness.
With these techniques, you can seamlessly integrate arg=val parsing into your Python CLI tools.