class documentation

Drop-in replacement for argparse.ArgumentParser that adds support for environment variables and .ini or .yaml-style config files.

Method __init__ Supports args of the argparse.ArgumentParser constructor as **kwargs, as well as the following additional args.
Method convert_item_to_command_line_arg Converts a config file or env var key + value to a list of commandline args to append to the commandline.
Method format_help Undocumented
Method format_values Returns a string with all args and settings and where they came from (eg. commandline, config file, environment variable or default)
Method get_command_line_key_for_unknown_config_file_setting Compute a commandline arg key to be used for a config file setting that doesn't correspond to any defined configargparse arg (and so doesn't have a user-specified commandline arg key).
Method get_items_for_config_file_output Converts the given settings back to a dictionary that can be passed to ConfigFormatParser.serialize(..).
Method get_possible_config_keys This method decides which actions can be set in a config file and what their keys will be. It returns a list of 0 or more config keys that can be used to set the given action's value in a config file.
Method get_source_to_settings_dict If called after parse_args() or parse_known_args(), returns a dict that contains up to 4 keys corresponding to where a given option's value is coming from: - "command_line" - "environment_variables" - "config_file" - "defaults" Each such key, will be mapped to another dictionary containing the options set via that method...
Method parse_args Supports all the same args as the argparse.ArgumentParser.parse_args(), as well as the following additional args.
Method parse_known_args Supports all the same args as the argparse.ArgumentParser.parse_args(), as well as the following additional args.
Method print_values Prints the format_values() string (to sys.stdout or another file).
Method write_config_file Write the given settings to output files.
Instance Variable exit_on_error Undocumented
Method _could_set_option Check whether a command line arg could set the given option.
Method _find_insertion_index Find the right index to insert config/env var args into the command line.
Method _find_subcommand_index Find where the subcommand is on the command line, if there is one.
Method _names_a_write_out_config_file_arg Check whether a command line arg would set a write-out-config-file arg.
Method _open_config_files Tries to parse config file path(s) from within command_line_args. Returns a list of opened config files, including files specified on the commandline as well as any default_config_files specified in the constructor that are present on disk.
Method _option_strings_that_override Find the option strings that, when already on the command line, mean an env var or config file value for the given action should be dropped.
Method _reachable_parsers Find this parser and every subparser these args could be handed to.
Method _reject_write_out_config_file_args Reject synthesized command line args that set a write-out-config-file arg.
Method _write_out_config_file_args Find the write-out-config-file args the given parsers define.
Instance Variable _add_config_file_help Undocumented
Instance Variable _add_env_var_help Undocumented
Instance Variable _auto_env_var_prefix Undocumented
Instance Variable _config_file_open_func Undocumented
Instance Variable _config_file_parser Undocumented
Instance Variable _default_config_files Undocumented
Instance Variable _ignore_unknown_config_file_keys Undocumented
Instance Variable _source_to_settings Undocumented
Instance Variable _write_out_config_file_paths Undocumented

Inherited from ArgumentParser:

Method add_subparsers Undocumented
Method convert_arg_line_to_args Undocumented
Method error error(message: string)
Method exit Undocumented
Method format_usage Undocumented
Method parse_intermixed_args Undocumented
Method parse_known_intermixed_args Undocumented
Method print_help Undocumented
Method print_usage Undocumented
Instance Variable add_help Undocumented
Instance Variable allow_abbrev Undocumented
Instance Variable epilog Undocumented
Instance Variable formatter_class Undocumented
Instance Variable fromfile_prefix_chars Undocumented
Instance Variable prog Undocumented
Instance Variable usage Undocumented
Method _add_action Undocumented
Method _check_value Undocumented
Method _get_formatter Undocumented
Method _get_kwargs Undocumented
Method _get_nargs_pattern Undocumented
Method _get_option_tuples Undocumented
Method _get_optional_actions Undocumented
Method _get_positional_actions Undocumented
Method _get_value Undocumented
Method _get_values Undocumented
Method _match_argument Undocumented
Method _match_arguments_partial Undocumented
Method _parse_known_args Undocumented
Method _parse_optional Undocumented
Method _print_message Undocumented
Method _read_args_from_files Undocumented
Instance Variable _optionals Undocumented
Instance Variable _positionals Undocumented
Instance Variable _subparsers Undocumented

Inherited from _AttributeHolder (via ArgumentParser):

Method __repr__ Undocumented
Method _get_args Undocumented

Inherited from _ActionsContainer (via ArgumentParser, _AttributeHolder):

Method add_argument add_argument(dest, ..., name=value, ...) add_argument(option_string, option_string, ..., name=value, ...)
Method add_argument_group Undocumented
Method add_mutually_exclusive_group Undocumented
Method get_default Undocumented
Method register Undocumented
Method set_defaults Undocumented
Instance Variable argument_default Undocumented
Instance Variable conflict_handler Undocumented
Instance Variable description Undocumented
Instance Variable prefix_chars Undocumented
Method _add_container_actions Undocumented
Method _check_conflict Undocumented
Method _get_handler Undocumented
Method _get_optional_kwargs Undocumented
Method _get_positional_kwargs Undocumented
Method _handle_conflict_error Undocumented
Method _handle_conflict_resolve Undocumented
Method _pop_action_class Undocumented
Method _registry_get Undocumented
Method _remove_action Undocumented
Instance Variable _action_groups Undocumented
Instance Variable _actions Undocumented
Instance Variable _defaults Undocumented
Instance Variable _has_negative_number_optionals Undocumented
Instance Variable _mutually_exclusive_groups Undocumented
Instance Variable _negative_number_matcher Undocumented
Instance Variable _option_string_actions Undocumented
Instance Variable _registries Undocumented
def __init__(self, *args, **kwargs): (source)

Supports args of the argparse.ArgumentParser constructor as **kwargs, as well as the following additional args.

Parameters
*argsUndocumented
add_config_file_helpWhether to add a description of config file syntax to the help message.
add_env_var_helpWhether to add something to the help message for args that can be set through environment variables.
auto_env_var_prefixIf set to a string instead of None, all config- file-settable options will become also settable via environment variables whose names are this prefix followed by the config file key, all in upper case. (eg. setting this to foo_ will allow an arg like --my-arg to also be set via the FOO_MY_ARG environment variable)
default_config_files

When specified, this list of config files will be parsed in order, with the values from each config file taking precedence over previous ones. This allows an application to look for config files in multiple standard locations such as the install directory, home directory, and/or current directory. Also, shell * syntax can be used to specify all conf files in a directory. For example:

["/etc/conf/app_config.ini",
"/etc/conf/conf-enabled/*.ini",
"~/.my_app_config.ini",
"./app_config.txt"]

Path entries may be strings, os.PathLike objects (e.g. pathlib.Path), or zero-argument callable functions that return an open file-like object containing config file contents. Any provided callable is invoked each time the parser opens config files, and the returned stream is closed by the parser after parsing. The callable must return a stream. This is useful for sourcing config from non-filesystem locations such as in-memory buffers, secrets managers, or HTTP responses.

ignore_unknown_config_file_keysIf true, settings that are found in a config file but don't correspond to any defined configargparse args will be ignored. If false, they will be processed and appended to the commandline like other args, and can be retrieved using parse_known_args() instead of parse_args()
config_file_open_funcfunction used to open a config file for reading or writing. Needs to return a file-like object.
config_file_parser_classconfigargparse.ConfigFileParser subclass which determines the config file format. configargparse comes with DefaultConfigFileParser and YAMLConfigFileParser.
args_for_setting_config_pathA list of one or more command line args to be used for specifying the config file path (eg. ["-c", "--config-file"]). Default: []
config_arg_is_requiredWhen args_for_setting_config_path is set, set this to True to always require users to provide a config path.
config_arg_help_messagethe help message to use for the args listed in args_for_setting_config_path.
args_for_writing_out_config_fileA list of one or more command line args to use for specifying a config file output path. If provided, these args cause configargparse to write out a config file with settings based on the other provided commandline args, environment variants and defaults, and then to exit. (eg. ["-w", "--write-out-config-file"]). Default: [] These args can only be set on the command line. A config file key that names one is an error, and they can't have an env_var, since either would let whoever controls those overwrite an arbitrary file.
write_out_config_file_arg_help_messageThe help message to use for the args in args_for_writing_out_config_file.
def convert_item_to_command_line_arg(self, action, key, value): (source)

Converts a config file or env var key + value to a list of commandline args to append to the commandline.

Parameters
actionThe argparse Action object for this setting, or None if this config file setting doesn't correspond to any defined configargparse arg.
keystring (config file key or env var name)
valueparsed value of type string or list
Returns
list[str]args
def format_help(self): (source)

Undocumented

def format_values(self): (source)

Returns a string with all args and settings and where they came from (eg. commandline, config file, environment variable or default)

Returns
strsource to settings string
def get_command_line_key_for_unknown_config_file_setting(self, key): (source)

Compute a commandline arg key to be used for a config file setting that doesn't correspond to any defined configargparse arg (and so doesn't have a user-specified commandline arg key).

Parameters
keyThe config file key that was being set.
Returns
strcommand line key
def get_items_for_config_file_output(self, source_to_settings, parsed_namespace): (source)

Converts the given settings back to a dictionary that can be passed to ConfigFormatParser.serialize(..).

Parameters
source_to_settingsthe dictionary described in parse_known_args()
parsed_namespacenamespace object created within parse_known_args()
Returns
OrderedDictwhere keys are strings and values are either strings or lists
def get_possible_config_keys(self, action): (source)

This method decides which actions can be set in a config file and what their keys will be. It returns a list of 0 or more config keys that can be used to set the given action's value in a config file.

Returns
list[str]keys
def get_source_to_settings_dict(self): (source)

If called after parse_args() or parse_known_args(), returns a dict that contains up to 4 keys corresponding to where a given option's value is coming from: - "command_line" - "environment_variables" - "config_file" - "defaults" Each such key, will be mapped to another dictionary containing the options set via that method. Here the key will be the option name, and the value will be a 2-tuple of the form (argparse.Action obj, str value).

Returns
dict[str, dict[str, tuple[argparse.Action, str]]]source to settings dict
def parse_args(self, args=None, namespace=None, config_file_contents=None, env_vars=os.environ): (source)

Supports all the same args as the argparse.ArgumentParser.parse_args(), as well as the following additional args.

Parameters
argsa list of args as in argparse, or a string (eg. "-x -y bla")
namespaceUndocumented
config_file_contentsString. Used for testing.
env_varsDictionary. Used for testing.
Returns
argparse.Namespacenamespace
def parse_known_args(self, args=None, namespace=None, config_file_contents=None, env_vars=os.environ, ignore_help_args=False): (source)

Supports all the same args as the argparse.ArgumentParser.parse_args(), as well as the following additional args.

Parameters
argsa list of args as in argparse, or a string (eg. "-x -y bla")
namespaceUndocumented
config_file_contents:str
env_vars:dict
ignore_help_args:boolThis flag determines behavior when user specifies --help or -h. If False, it will have the default behavior - printing help and exiting. If True, it won't do either.
Returns
tuple[argparse.Namespace, list[str]]tuple namescpace, unknown_args
def print_values(self, file=sys.stdout): (source)

Prints the format_values() string (to sys.stdout or another file).

def write_config_file(self, parsed_namespace, output_file_paths, exit_after=False): (source)

Write the given settings to output files.

Parameters
parsed_namespacenamespace object created within parse_known_args()
output_file_pathsany number of file paths to write the config to
exit_afterwhether to exit the program after writing the config files
exit_on_error: bool = (source)

Undocumented

def _could_set_option(self, arg_string, option_string): (source)

Check whether a command line arg could set the given option.

This covers every form argparse accepts: the option on its own, with its value attached after an = (or, for a short option, straight after it), bundled with other short options, and abbreviated. Where argparse would need to look at the rest of the command line to decide, this says yes, since it is used to reject args that must not reach an option at all, and being wrong in that direction only costs an error message.

Parameters
arg_stringa single command line arg.
option_stringan option string of the option to look for.
Returns
boolwhether the arg could set the option
def _find_insertion_index(self, args): (source)

Find the right index to insert config/env var args into the command line.

Inserts before the -- separator if present, before a subparser command so the parent parser sees injected args first, before the first optional arg, or at position 0 when a REMAINDER positional exists. Falls back to appending.

def _find_subcommand_index(self, args): (source)

Find where the subcommand is on the command line, if there is one.

Parameters
argsthe command line args.
Returns
int or Nonethe index of the first arg naming a subcommand
def _names_a_write_out_config_file_arg(self, arg_string, parsers): (source)

Check whether a command line arg would set a write-out-config-file arg.

Parameters
arg_stringa single command line arg.
parsersthe parsers that could end up parsing it.
Returns
boolwhether it names a write-out-config-file arg
def _open_config_files(self, command_line_args): (source)

Tries to parse config file path(s) from within command_line_args. Returns a list of opened config files, including files specified on the commandline as well as any default_config_files specified in the constructor that are present on disk.

Parameters
command_line_argsList of all args
Returns
list[tuple[io.IOBase, str]]list of (stream, source_label) pairs. The source_label is unique per entry (file path for path entries; "<entry_label>[<index>]" for callable entries), so different entries cannot collapse into a single source key in format_values().
def _option_strings_that_override(self, action): (source)

Find the option strings that, when already on the command line, mean an env var or config file value for the given action should be dropped.

These are the action's own option strings plus those of every other action in the same mutually exclusive group, mirroring the conflicts argparse checks for. Without the latter, a config file value for one member of a group would clash with a different member given on the command line instead of being overridden by it (see issue #164).

Parameters
actionthe argparse.Action to find overriding option strings for.
Returns
list[str]the option strings
def _reachable_parsers(self): (source)

Find this parser and every subparser these args could be handed to.

A subparser is given the args this parser has put together and treats them as its own command line, and argparse parses it into this parser's namespace, so both what a subparser accepts and what it stores matter here. Subparsers that aren't ConfigArgParse parsers are walked through as well, since one of them can hold a subparser that is.

Returns
list[argparse.ArgumentParser]this parser and its subparsers
def _reject_write_out_config_file_args(self, synthesized_args, source_description, parsers): (source)

Reject synthesized command line args that set a write-out-config-file arg.

Config file entries and environment variables are turned into command line args and then parsed like any others, so either one's key or its value can end up naming an arg. A write-out-config-file arg overwrites the path it is given and then exits the program, so only the real command line may set one: otherwise whoever controls a config file the program reads could destroy an arbitrary file without the user passing any args at all. (This is also why get_possible_config_keys() keeps these args out of the keys a config file can set.)

These args are checked against every parser reachable from this one, not just the one that looks like it will parse them. Which subcommand runs can't be told from the args: an option's value reads exactly like a subcommand name, and the synthesized args can name a subcommand themselves. So a config file may not name a write-out arg anywhere in the parser tree, which costs an error on a key named after one on a subcommand that wasn't going to run.

Parameters
synthesized_argscommand line args built from a config file or from environment variables, before they are added to the real ones.
source_descriptionwhere they came from, for the error message.
parsersthe parsers that could end up parsing them.
Returns
boolwhether the args may be used. error() is meant to stop the program, but a program can override exit(), so this says so rather than counting on the call not returning.
def _write_out_config_file_args(self, parsers): (source)

Find the write-out-config-file args the given parsers define.

Parameters
parsersthe parsers to look in.
Returns
listeach such arg as an (argparse.ArgumentParser, argparse.Action) pair, since it's the parser an arg belongs to that decides which command line args can set it.
_add_config_file_help: bool = (source)

Undocumented

_add_env_var_help: bool = (source)

Undocumented

_auto_env_var_prefix = (source)

Undocumented

_config_file_open_func = (source)

Undocumented

_config_file_parser = (source)

Undocumented

_default_config_files = (source)

Undocumented

_ignore_unknown_config_file_keys = (source)

Undocumented

_source_to_settings = (source)

Undocumented

_write_out_config_file_paths = (source)

Undocumented