API Reference
ConditionalArgumentParser
- class conditional_parser.ConditionalArgumentParser(*args, **kwargs)[source]
Bases:
ArgumentParserAn ArgumentParser that supports conditional arguments based on other argument values.
This parser extends the standard ArgumentParser to allow adding arguments that only appear when certain conditions are met. This is useful for creating command-line interfaces where the value of one argument determines whether another argument is required.
Example
>>> parser = ConditionalArgumentParser() >>> parser.add_argument('--format', choices=['json', 'csv'], default='json') >>> parser.add_conditional('format', 'csv', '--delimiter', ... help='Delimiter for CSV output') >>> args = parser.parse_args(['--format', 'csv', '--delimiter', ',']) >>> print(args.delimiter) ','
- __init__(*args, **kwargs)[source]
Initialize the ConditionalArgumentParser.
- Parameters:
*args (Any) – Positional arguments passed to ArgumentParser
**kwargs (Any) – Keyword arguments passed to ArgumentParser
Notes
See the standard argparse.ArgumentParser documentation for details on available initialization parameters.
- add_conditional(dest: str, cond: Any | Callable, *args, **kwargs) None[source]
Add a conditional argument to the parser.
This method adds an argument that is only included when the value of a parent argument matches a specified condition. The condition can be either a fixed value or a callable function that evaluates the parent argument’s value.
- Parameters:
dest (str) – The destination of the parent argument to compare.
cond (Union[Any, Callable]) – A value or callable function that determines whether to add the conditional argument. If callable, it will be called on the value of dest. If not callable, it will be compared to the value of dest.
*args (Any) – The arguments to add when the condition is met (via the standard add_argument method).
**kwargs (Any) – The keyword arguments to add when the condition is met (via the standard add_argument method).
Examples
>>> parser = ConditionalArgumentParser() >>> parser.add_argument('--format', choices=['json', 'csv']) >>> parser.add_conditional('format', 'csv', '--delimiter', ... help='Delimiter for CSV output') >>> args = parser.parse_args(['--format', 'csv', '--delimiter', ',']) >>> print(args.delimiter) ','
- parse_args(args: List[str] | None = None, namespace: Namespace | None = None) Namespace[source]
Parse command line arguments including conditional arguments.
This method extends the standard ArgumentParser.parse_args() by first evaluating which conditional arguments need to be added based on the values of their parent arguments, then parsing all arguments together.
- Parameters:
args (Optional[List[str]], default=None) – List of strings to parse. If None, default to sys.argv[1:].
namespace (Optional[Namespace], default=None) – An object to store the parsed arguments. If None, a new Namespace object is created.
- Returns:
A namespace containing the parsed arguments.
- Return type:
Namespace
Examples
>>> parser = ConditionalArgumentParser() >>> parser.add_argument('--format', choices=['json', 'csv']) >>> parser.add_conditional('format', 'csv', '--delimiter') >>> args = parser.parse_args(['--format', 'csv', '--delimiter', ',']) >>> print(args.delimiter) ','
The ConditionalArgumentParser extends Python’s ArgumentParser to support conditional arguments. It inherits all standard ArgumentParser functionality while adding the ability to specify arguments that only appear when certain conditions are met.
Key Methods
The main addition to ArgumentParser is the add_conditional() method, which allows you to add a conditional argument to the parser. This method takes the same arguments as the standard add_argument() method, with the addition of a dest and cond arguments which specify the destination in the namespace to check for the condition and the condition itself, respectively.
Note
The dest argument is the name of the argument in the namespace that will be checked for the condition. The nomenclature might be a bit confusing; it’s used to be consistent with how the ArgumentParser assigns arguments to the namespace.
What you are looking for is whatever attribute name you’d use to get the value of the argument from the output of parse_args(). So, for example:
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("--use-regularization", default=False, action="store_true")
parser.add_argument("--nohyphen", default=False, action="store_true")
args = parser.parse_args(["--use-regularization"])
# The "dest" of --use-regularization is "use_regularization"
print(args.use_regularization) # True
# The "dest" of --nohyphen is "nohyphen"
print(args.nohyphen) # False
Internal Methods
The following methods are used internally by ConditionalArgumentParser to manage conditional arguments:
- _prepare_conditionals(_parser, args, already_added)
Recursively prepare and add conditional arguments to the parser based on the values of their parent arguments.
- Parameters:
- Returns:
The parser with all required conditional arguments added
- Return type:
ArgumentParser
- _prepare_help(_parser)
Prepare the help parser to show all conditional arguments in the help output with modified help text.
- Parameters:
_parser (ArgumentParser) – The parser to which help text will be added
- Returns:
The parser with all conditional arguments and their help text added
- Return type:
ArgumentParser
- _make_callable(cond)
Convert a condition into a callable function.
- Parameters:
cond (Union[Callable, Any]) – Either a callable or a value to compare against
- Returns:
A function that takes one argument and returns a boolean
- Return type:
Callable
- Raises:
ValueError – If cond is callable but doesn’t accept exactly one argument
- _callable_representation(parent, cond)
Get a string representation of a condition for help text.
- _conditionals_ready(namespace, already_added)
Check if all required conditional arguments have been added to the parser.
- _conditional_required(namespace, parent, already_added, idx)
Check if a specific conditional argument needs to be added.
- Parameters:
- Returns:
True if the conditional argument needs to be added
- Return type: