module documentation

A drop-in replacement for argparse that allows options to also be set via config files and/or environment variables.

See Also
configargparse.ArgumentParser, configargparse.add_argument
Class ArgumentDefaultsRawHelpFormatter HelpFormatter that adds default values AND doesn't do line-wrapping
Class ArgumentParser Drop-in replacement for argparse.ArgumentParser that adds support for environment variables and .ini or .yaml-style config files.
Class CompositeConfigParser Create a config parser composed of other config file parsers, each given as a ConfigFileParser instance or class (a class is instantiated with no args).
Class ConfigFileParser This abstract class can be extended to add support for new config file formats
Class ConfigparserConfigFileParser parses INI files using pythons configparser.
Class DefaultConfigFileParser Based on a simplified subset of INI and YAML formats. Here is the supported syntax
Class IniConfigParser Create a INI parser bounded to the list of provided sections. Optionaly convert multiline strings to list.
Class TomlConfigParser Create a TOML parser bounded to the list of provided sections. Useful to read settings from a project file such as pyproject.toml.
Class YAMLConfigFileParser Parses YAML config files. Depends on the PyYAML module. https://pypi.python.org/pypi/PyYAML
Exception ConfigFileParserException Raised when config file parsing failed.
Exception ConfigFileParserMissingDependency Raised when an optional dependency is missing.
Function add_argument This method supports the same args as ArgumentParser.add_argument(..) as well as the additional args below.
Function already_on_command_line Utility method for checking if any of the potential_command_line_args is already present in existing_args.
Function get_argument_parser Returns the global ArgumentParser instance with the given name. The 1st time this function is called, a new ArgumentParser instance will be created for the given name, and any args other than "name" will be passed on to the ArgumentParser constructor.
Function get_toml_section Given some TOML data (as loaded with toml.load()), returns the requested section of the data. Returns None if the section is not found.
Function init_argument_parser Creates a global ArgumentParser instance with the given name, passing any args other than "name" to the ArgumentParser constructor. This instance can then be retrieved using get_argument_parser(..)
Function is_quoted Detect whether a string is a quoted representation.
Function parse_toml_section_name Parse a TOML section name to a sequence of strings.
Function unquote_str Unquote a maybe quoted string representation. If the string is not detected as being a quoted representation, it returns the same string as passed. It supports all kinds of python quotes: """, ''', " and ...
Variable ACTION_TYPES_THAT_DONT_NEED_A_VALUE Undocumented
Variable is_boolean_optional_action Undocumented
Class _WriteOutConfigFileActionMixin Remembers the path this arg was given, on the parser that parsed it.
Function _action_takes_a_list_of_values Check whether argparse stores a list of values for an action.
Function _add_config_values_as_str_except_lists Add a config file's values to result the way argparse will read them.
Function _close_config_streams Close each config file stream, ignoring any error closing one raises.
Function _configparser_value_is_evaluated_as_list Check whether ConfigparserConfigFileParser.parse() reads a value as a list.
Function _convert_parsed_value_to_config_file_value Convert a parsed arg value to the value a config file should hold for it.
Function _convert_to_types_every_config_file_parser_can_write Convert a value to a plain str, int, float, bool or list of those.
Function _default_can_be_written_so_it_reads_back Check whether a default can be written to a config file and read back.
Function _dispatches_to_subparsers Check whether an action hands the rest of the command line to a subparser.
Function _evaluate_list_literal Evaluate a config file value written as a Python list literal.
Function _is_variable_length_list Check whether a value is a list for an option that takes any number of values.
Function _keep_literal_or_convert_to_str Return a list element as it should be written into a list repr.
Function _list_literal_that_reads_back_as_the_list Write a list as a Python list literal that ast.literal_eval reads back.
Function _parse_bracketed_list_value Turns a config file or env var value written as a list into a list.
Function _parse_number_of_times_to_give_a_count_flag Read a config file or env var value for a count option as a number.
Function _quote_ini_value_if_needed_to_read_back_unchanged Write a string the way IniConfigParser.parse() reads back unchanged.
Function _read_configparser_section_items Read one section's keys and values from a configparser.ConfigParser.
Function _replace_enum_members_its_type_reads_by_name_with_their_names Write an Enum member as its name where the action's type= needs that.
Function _subparsers_of Find a parser and every subparser reachable from it.
Constant _COMMAND_LINE_SOURCE_KEY Undocumented
Constant _CONFIG_FILE_SOURCE_KEY Undocumented
Constant _DEFAULTS_SOURCE_KEY Undocumented
Constant _ENV_VAR_SOURCE_KEY Undocumented
Constant _QUOTED_STR_REGEX Undocumented
Constant _TRIPLE_QUOTED_STR_REGEX Undocumented
Variable _parsers Undocumented
def add_argument(self, *args, **kwargs): (source)

This method supports the same args as ArgumentParser.add_argument(..) as well as the additional args below.

Parameters
selfUndocumented
*argsUndocumented
env_varIf set, the value of this environment variable will override any config file or default values for this arg (but can itself be overridden on the commandline). Also, if auto_env_var_prefix is set in the constructor, this env var name will be used instead of the automatic name.
is_config_file_argIf True, this arg is treated as a config file path This provides an alternative way to specify config files in place of the ArgumentParser(fromfile_prefix_chars=..) mechanism. Default: False
is_write_out_config_file_argIf True, this arg will be treated as a config file path, and, when it is specified on the command line, will cause configargparse to write all current commandline args to this file as config options and then exit. It can only be set on the command line: a config file key that names it is an error, and it can't be combined with env_var, nor be a positional arg, since a config file value would be indistinguishable from a path the user typed and could overwrite an arbitrary file. Default: False
Returns
argparse.Actionthe new argparse action
def already_on_command_line(existing_args_list, potential_command_line_args, prefix_chars, parser=None): (source)

Utility method for checking if any of the potential_command_line_args is already present in existing_args.

Parameters
existing_args_listthe command line args.
potential_command_line_argsthe option strings to look for.
prefix_charsthe chars that start an option.
parserthe ArgumentParser the args are for. When given, only the args that parser reads itself are looked at (not those after a subcommand, which argparse hands to the subparser, nor those after '--' or that a REMAINDER positional or option takes), and every form argparse accepts is recognized, such as '-vv' for '-v' or '-Ifoo' for '-I'. Otherwise only an option string on its own or followed by '=value' is, in the args before any '--'.
Returns
boolalready on command line?
def get_argument_parser(name=None, **kwargs): (source)

Returns the global ArgumentParser instance with the given name. The 1st time this function is called, a new ArgumentParser instance will be created for the given name, and any args other than "name" will be passed on to the ArgumentParser constructor.

def get_toml_section(data, section): (source)

Given some TOML data (as loaded with toml.load()), returns the requested section of the data. Returns None if the section is not found.

def init_argument_parser(name=None, **kwargs): (source)

Creates a global ArgumentParser instance with the given name, passing any args other than "name" to the ArgumentParser constructor. This instance can then be retrieved using get_argument_parser(..)

@functools.lru_cache(maxsize=256, typed=True)
def is_quoted(text, triple=True): (source)

Detect whether a string is a quoted representation.

Parameters
textUndocumented
tripleAlso match tripple quoted strings.
def parse_toml_section_name(section_name): (source)

Parse a TOML section name to a sequence of strings.

The following names are all valid:

"a.b.c"            # this is best practice -> returns ("a", "b", "c")
" d.e.f "          # same as [d.e.f] -> returns ("d", "e", "f")
" g .  h  . i "    # same as [g.h.i] -> returns ("g", "h", "i")
' j . "ʞ" . "l" '  # same as [j."ʞ"."l"], double or simple quotes here are supported. -> returns ("j", "ʞ", "l")
def unquote_str(text, triple=True): (source)

Unquote a maybe quoted string representation. If the string is not detected as being a quoted representation, it returns the same string as passed. It supports all kinds of python quotes: """, ''', " and '.

Parameters
textUndocumented
tripleAlso unquote tripple quoted strings.
Raises
ValueErrorIf the string is detected as beeing quoted but literal_eval() fails to evaluate it as string. This would be a bug in the regex.
ACTION_TYPES_THAT_DONT_NEED_A_VALUE = (source)

Undocumented

is_boolean_optional_action = (source)

Undocumented

def _action_takes_a_list_of_values(action): (source)

Check whether argparse stores a list of values for an action.

It does when nargs is '*', '+' or a number, even 1.

Parameters
actionan argparse action.
Returns
boolwhether it does
def _add_config_values_as_str_except_lists(values_by_key, result): (source)

Add a config file's values to result the way argparse will read them.

Anything that is not a list is converted to a string, since config values are passed to argparse as command line args, and argparse converts them back to a boolean, int or whatever the arg's type is. Keys set to None are left out.

Parameters
values_by_keythe keys and values a YAML or TOML parser read.
resultthe OrderedDict to add them to.
def _close_config_streams(streams_and_source_labels): (source)

Close each config file stream, ignoring any error closing one raises.

Parameters
streams_and_source_labels(stream, source label) pairs.
def _configparser_value_is_evaluated_as_list(value): (source)

Check whether ConfigparserConfigFileParser.parse() reads a value as a list.

Parameters
valuethe value as written, with newlines replaced by spaces.
Returns
boolwhether it has square brackets that aren't inside a {...} dict
def _convert_parsed_value_to_config_file_value(action, value): (source)

Convert a parsed arg value to the value a config file should hold for it.

For a flag (store_true, store_false, store_const or append_const), the config file value says whether to invoke the flag, not what it stores, so it is "true" exactly when the parsed value is (or, for append_const, holds) the one the flag stores. Other booleans are written in lowercase too, so values from the command line and from environment variables are written the same way. A tuple for an option that takes a list of values, such as a default of (640, 480) for nargs=2, is written as a list.

Values of other types, such as a pathlib.Path default, are written as str(), since every config file format can write a string and read it back. (Such a value that argparse made from a string has already been replaced with that string, see ArgumentParser._replace_parsed_values_with_the_strings_they_came_from().)

Parameters
actionthe action the value was parsed for.
valuethe value the parser stored for the action.
Returns
object"true" or "false" for flags and booleans, otherwise the value with anything that isn't a str, int, float, bool or list converted to a str.
def _convert_to_types_every_config_file_parser_can_write(value): (source)

Convert a value to a plain str, int, float, bool or list of those.

An Enum member is written as its value, which is what a type= callable like type=SomeEnum takes back (one that takes its name instead has already been given the name, see _replace_enum_members_its_type_reads_by_name_with_their_names()). Some config file writers only handle the built-in types themselves, so a subclass of one (eg. a str or int Enum's value, or an IntEnum) becomes that built-in type, and anything else becomes a str.

Parameters
valuea parsed arg value, or an element of a list value.
Returns
objectthe value, with each list element converted the same way
def _default_can_be_written_so_it_reads_back(value): (source)

Check whether a default can be written to a config file and read back.

It can when it is a str, int, float, bool, Enum or path, or a list or tuple of these that isn't empty. Read back, an empty list sets an option to no values, which argparse rejects for nargs='+', and str() of other objects, such as the open file in a default of sys.stdout, isn't anything the option's type= can take.

Parameters
valuethe default, after any string it was converted from has been put back.
Returns
boolwhether it can
def _dispatches_to_subparsers(action): (source)

Check whether an action hands the rest of the command line to a subparser.

Nearly always this is an argparse._SubParsersAction, but a program can register a class of its own for the job, so recognize the shape too: a mapping of subcommand names to parsers, taking the rest of the args.

Parameters
actionthe action to check.
Returns
boolwhether it dispatches to subparsers
def _evaluate_list_literal(text): (source)

Evaluate a config file value written as a Python list literal.

Parameters
textthe value, eg. "['a', 'b']".
Returns
the evaluated value
Raises
ConfigFileParserExceptionif the text isn't a valid literal.
def _is_variable_length_list(action, value): (source)

Check whether a value is a list for an option that takes any number of values.

Parameters
actionthe action the value is for, or None for an unknown key.
valuethe value from a config file or env var.
Returns
boolwhether argparse would read the args after it as more values
def _keep_literal_or_convert_to_str(value): (source)

Return a list element as it should be written into a list repr.

Parameters
valuean element of a list value.
Returns
objectthe value unchanged if ast.literal_eval of its repr gives it back, otherwise str(value) (e.g. for a Path, or inf).
def _list_literal_that_reads_back_as_the_list(value): (source)

Write a list as a Python list literal that ast.literal_eval reads back.

Parameters
valuea list value, whose elements may be lists themselves.
Returns
strthe literal, with each element (and each element of an inner list) that a literal can't hold, such as a Path or inf, as its str()
def _parse_bracketed_list_value(value): (source)

Turns a config file or env var value written as a list into a list.

Parameters
valuethe value as written, eg. '["a", "b"]' or '[a, b]'.
Returns
the list, or the value unchanged if it isn't in square brackets
def _parse_number_of_times_to_give_a_count_flag(value): (source)

Read a config file or env var value for a count option as a number.

Accepts anything int() accepts, such as "2", "+2", " 2 ", "2n" (an env var filled from a file often ends in a newline) or "1_000", as long as the number isn't negative: a flag can't be given a negative number of times.

Parameters
valuethe string from the config file or env var.
Returns
int or Nonethe number, or None if value isn't a whole number of 0 or more
def _quote_ini_value_if_needed_to_read_back_unchanged(value): (source)

Write a string the way IniConfigParser.parse() reads back unchanged.

parse() strips the whitespace around a value, skips an empty one, reads a value in square brackets as a list and one on several lines as a list (if split_ml_text_to_list is set), and unquotes a quoted one. A list element written on a line of its own that starts with '#' or ';' would be read as a comment. A value any of that would change is written as a Python string literal, which parse() unquotes back to the same string.

Parameters
valuethe string to write.
Returns
strthe value, or its Python string literal
def _read_configparser_section_items(config, section): (source)

Read one section's keys and values from a configparser.ConfigParser.

configparser expands %(name)s references while reading values, so a stray % fails here rather than when the file is read.

Parameters
configthe configparser.ConfigParser the file was read into.
sectionthe name of the section to read.
Returns
listthe section's (key, value) pairs
Raises
ConfigFileParserExceptionif a value's % or %(name)s can't be expanded.
def _replace_enum_members_its_type_reads_by_name_with_their_names(action, value): (source)

Write an Enum member as its name where the action's type= needs that.

An Enum member is otherwise written as its value (see _convert_to_types_every_config_file_parser_can_write()), which suits type=SomeEnum, but not a lookup by name such as type=lambda s: SomeEnum[s]. So a member that the type= callable doesn't read back from its value, but does from its name, is replaced with its name.

Parameters
actionthe action the value was parsed for.
valuea parsed arg value, or an element of a list value.
Returns
objectthe value, with each such member replaced by its name
def _subparsers_of(parser, seen=None): (source)

Find a parser and every subparser reachable from it.

Parameters
parserthe parser to start from.
seenids of the parsers already visited, so that a subparser leading back to one of its own ancestors doesn't loop forever.
Returns
list[argparse.ArgumentParser]the parser and its subparsers
_COMMAND_LINE_SOURCE_KEY: str = (source)

Undocumented

Value
'command_line'
_CONFIG_FILE_SOURCE_KEY: str = (source)

Undocumented

Value
'config_file'
_DEFAULTS_SOURCE_KEY: str = (source)

Undocumented

Value
'defaults'
_ENV_VAR_SOURCE_KEY: str = (source)

Undocumented

Value
'environment_variables'
_QUOTED_STR_REGEX = (source)

Undocumented

Value
re.compile(r'(^"(?:\\.|[^"\\])*"$)|(^\'(?:\\.|[^\'\\])*\'$)')
_TRIPLE_QUOTED_STR_REGEX = (source)

Undocumented

Value
re.compile(r'(^"""(\s+)?(([^"]|"([^"]|"[^"]))*(""?)?)?(\s+)?(?:\\.|[^"\\])?"""$)↵
|(^\'\'\'(\s+)?(([^\']|\'([^\']|\'[^\']))*(\'\'?)?)?(\s+)?(?:\\.|[^\'\\])?\'\'\'↵
$)',
           re.DOTALL)
_parsers: dict = (source)

Undocumented