API reference

class multiconfparse.Action(name, nargs=None, type=<class 'str'>, required=False, default=NOT_GIVEN, choices=None, help=None, include_sources=None, exclude_sources=None)

Abstract base class config actions.

Classes to support actions should:

  • Inherit from Action.

  • Implement the accumulate_processed_value() method:

    accumulate_processed_value(current, new)

    Combine a new processed value for this config with any existing value.

    This method must be implemented by subclasses.

    Arguments:

    • current: the current value for this config item (which may be NOT_GIVEN or MENTIONED_WITHOUT_VALUE).
    • new: The new value (which will never be NOT_GIVEN but may be MENTIONED_WITHOUT_VALUE) to combine with the current value for the config item.

    The current and new will have:

    • been coerced to the config item’s type;
    • been checked for nargs and choices validity;
    • had values for nargs == 1 converted to a single element list.

    Returns: the new combined value, which must not be NOT_GIVEN.

    For example, the accumulate_processed_value() method for the append action is:

    def accumulate_processed_value(self, current, new):
        assert new is not NOT_GIVEN
        if self.nargs == "?" and new is MENTIONED_WITHOUT_VALUE:
            new = self.const
        if current is NOT_GIVEN:
            return [new]
        return current + [new]
    
  • Have a name class attribute set to the name of the action that the class implements.

  • Have an __init__() method that accepts arguments passed to ConfigParser.add_config() calls by the user (except the action argument) and which calls Action.__init__() with any of those arguments which are not specific to the action handled by the class. I.e.:

    • name;
    • nargs;
    • type;
    • required;
    • default;
    • choices;
    • help;
    • include_sources;
    • exclude_sources.

    These arguments will be assigned to attributes of the Action object being created (perhaps after some processing or validation) that are available for access by subclasses. The names of the attributes are the same as the argument names.

    It is recommended that passing the arguments to Action.__init__() is done by the subclass __init__ method accepting a **kwargs argument to collect any arguments that are not used or modified by the action class, then passing that **kwargs argument to Action.__init__(). The action class may also want pass some arguments that aren’t specified by the user if the value of those arguments is implied by the action. For example, the store_const action class has the following __init__ method:

    def __init__(self, const, **kwargs):
        super().__init__(
            nargs=0,
            type=mentioned_without_value,
            required=False,
            choices=None,
            **kwargs,
        )
        self.const = const
    

    This ensures that an exception is raised if the user specifies nargs, type, required, or choices arguments when adding a store_const action because if the user specifies those arguments they will be given twice in the call to Action.__init__().

The full example of the class for the store_const action is:

class StoreConstAction(Action):
    name = "store_const"

    def __init__(self, const, **kwargs):
        super().__init__(
            nargs=0,
            type=mentioned_without_value,
            required=False,
            choices=None,
            **kwargs,
        )
        self.const = const

    def accumulate_processed_value(self, current, new):
        assert new is MENTIONED_WITHOUT_VALUE
        return self.const
accumulate_processed_value(current, new)

Combine a new processed value for this config with any existing value.

This method must be implemented by subclasses.

Arguments:

  • current: the current value for this config item (which may be NOT_GIVEN or MENTIONED_WITHOUT_VALUE).
  • new: The new value (which will never be NOT_GIVEN but may be MENTIONED_WITHOUT_VALUE) to combine with the current value for the config item.

The current and new will have:

  • been coerced to the config item’s type;
  • been checked for nargs and choices validity;
  • had values for nargs == 1 converted to a single element list.

Returns: the new combined value, which must not be NOT_GIVEN.

class multiconfparse.AppendAction(const=None, **kwargs)

The append action stores the value for each mention of a config item in a list. The list is sorted according to the priorities of the mentions of the config item, lower priorities first. The Behaviour is based on the append argparse action.

Notes about the arguments to ConfigParser.add_config():

  • nargs == 0 is not allowed. The default nargs value is None.

    When nargs >= 1, nargs == "+" or nargs == "*", each value in the list for the config item is itself a list containing the arguments for a mention of the config item.

  • The const argument is only accepted when nargs == "?".

  • The default argument (if it is given and is not SUPPRESS) is used as the initial list of values. This means that the default value is incorporated into the final value for the config item, even if the config item is mentioned in a source.

Examples:

parser = multiconfparse.ConfigParser()
parser.add_config("config_item1", action="append", default=["v1"])
parser.add_source("dict", {"config_item1": "v2"}, priority=2)
parser.add_source("dict", {"config_item1": "v3"}, priority=1)
parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": ["v1", "v3", "v2"],
# }
parser = multiconfparse.ConfigParser()
parser.add_config(
    "config_item1",
    action="append",
    nargs="?",
    const="v0",
)
parser.parse_config()
parser.add_source("dict", {"config_item1": "v1"}, priority=2)
parser.add_source("dict", {"config_item1": None}, priority=1)
# -> multiconfparse.Namespace {
#   "config_item1": ["v0", "v1"],
# }
class multiconfparse.ArgparseSource(config_specs, priority=20)

Obtains config values from an argparse.ArgumentParser.

Do not create ArgparseSource objects directly, add them to a ConfigParser object using ConfigParser.add_source(). For example:

parser = multiconfparse.ConfigParser()
parser.add_config("config_item1")
parser.add_config("config_item2", nargs=2, type=int)
parser.add_config("config_item3", action="store_true")
argparse_source = parser.add_source("argparse")

argparse_parser = argparse.ArgumentParser()
argparse_parser.add_argument("arg1")
argparse_parser.add_argument("--opt1", type=int, action="append")
argparse_source.add_configs_to_argparse_parser(argparse_parser)

args = argparse_parser.parse_args((
    "arg1_value --config-item1 v1 --config-item2 1 2 --opt1 opt1_v1 "
    "--config-item-3 --opt1 opt1_v2"
).split())

argparse_source.notify_parsed_args(args)

config_parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": "v1",
#   "config_item2": [1, 2],
#   "config_item3": True,
# }

The argparse source does not create an argparse.ArgumentParser for you. This is to allow extra command line arguments to be added to an argparse.ArgumentParser that are not config items. Instead ArgparseSource, which implements the argparse source provides two methods to provide communication with the argparse.ArgumentParser:

add_configs_to_argparse_parser(argparse_parser)

Add arguments to an argparse.ArgumentParser for config items.

notify_parsed_args(argparse_namespace)

Notify the argparse source of the argparse.Namespace object returned by argparse.ArgumentParser.parse_args().

If you don’t need to add command line arguments other than for config items, see SimpleArgparseSource which implements the simple_argparse source.

The arguments of ConfigParser.add_source() for the argparse source are:

  • source (required, positional): "argparse"
  • priority (optional, keyword): The priority for the source. The default priority for an argparse source is 20.

Note that:

  • The name of the command line argument for a config item is the config item’s name with underscores (_) converted to hyphens (-) and prefixed with --.
add_configs_to_argparse_parser(argparse_parser)

Add arguments to an argparse.ArgumentParser for config items.

notify_parsed_args(argparse_namespace)

Notify the argparse source of the argparse.Namespace object returned by argparse.ArgumentParser.parse_args().

class multiconfparse.ConfigParser(config_default=NOT_GIVEN)

Create a new ConfigParser object. Options are:

  • config_default: the default value to use in the Namespace returned by parse_config() for config items for which no value was found.

    The default behaviour (when config_default is NOT_GIVEN) is to represent these config items with the value None.

    Set config_default to SUPPRESS to prevent these configs from having an attribute set in the Namespace at all.

add_config(name, **kwargs)

Add a config item to the ConfigParser.

The arguments that apply to all config items are:

  • name (required, positional): the name of the config item.

    In the Namespace object returned by parse_config(), the name of the attribute used for this config item will be name and must be a valid Python identifier.

    name is also used by source Source classes to generate the strings that will be used to find the config in config sources. The Source classes may, use a modified version of name, however. For example, the argparse and simple_argparse sources will convert underscores (_) to hyphens (-) and add a -- prefix, so if a config item had the name "config_item1", the argparse and simple_argparse sources would use the option string "--config-item1".

  • action (optional, keyword): the name of the action that should be performed when a config item is found in a config source. The default action is "store", and the built-in actions are described briefly below. See Actions for more detailed information about the built-in actions and creating your own actions. The built-in actions are all based on argparse actions so the argparse documentation may also provide useful information.

    • store: this action just stores the highest priority value for config item.
    • store_const: this stores the value specified in the const argument.
    • store_true: this stores the value True and sets the default argument to False. It is a special case of store_const.
    • store_false: this stores the value False and sets the default argument to True. It is a special case of store_const.
    • append: this creates a list containing every value seen (with lower priority values first). When nargs >= 1, nargs == "+" or nargs == "*", each value in the list s iteself a list containing the arguments for a mention of the config item.
    • count: this stores the number of mentions of the config item.
    • extend: this creates a list containing every value seen (with lower priority values first). Unlike append, when nargs >= 1, nargs == "+" or nargs == "*", arguments for mentions of the config item are not placed in separate sublists for each mention.
  • default: the default value for this config item. Note that some actions will incorporate the default value into the final value for the config item even if the config item is mentioned in one of the sources (e.g. append, count and extend).

    Note that the default value for all config items can also be set by passing a value for the config_default argument of ConfigParser. If both the config_default argument to ConfigParser and the default argument to add_config() are used then only the default argument to add_config() is used.

    If a default value is not provided for the config item by the default argument, the config_default argument or by the action class (like e.g. store_true does), then the final value for the config will be None if the config item is not mentioned in any source.

    The special value SUPPRESS can be passed as the default argument. In this case, if the config item is not mentioned in any source, it will not be given an attribute in the Namespace object returned by parse_config().

  • exclude_sources (optional, keyword): a collection of source names or Source classes that should ignore this config item. This argument is mutually exclusive with include_sources. If neither exclude_sources nor include_sources is given, the config item will be looked for by all sources added to the ConfigParser.

  • include_sources (optional, keyword): a collection of source names or Source classes that should look for this config item. This argument is mutually exclusive with exclude_sources. If neither exclude_sources nor include_sources is given, the config item will be looked for by all sources added to the ConfigParser.

  • help: the help text/description for the config item.

The other arguments are all keyword arguments and are passed on to the class that implements the config items action and may have different default values or may not even be valid for all actions. See Actions for action specific documentation.

  • nargs: specifies the number of arguments that the config item accepts. The values that nargs can take are:

    • None: the config item will take a single argument.
    • 0: the config item will take no arguments. This value is usually not given to add_config() but may be implicit for an action (e.g. store_const or count).
    • An int N >= 1: the config item will take N arguments and the value for a mention of the config item will be a list containing each argument. In particular, when nargs == 1 the value for each mention of a config item will be a list containing a single element.
    • "?": The config item will take a single optional argument. When the config item is mentioned without an accompanying value, the value for the mention is the value of the config item’s const argument.
    • "*": The config item will take zero or more arguments and the value for a mention of the config item will be a list containing each argument.
    • "+" The config item will take one or more arguments and the value for a mention of the config item will be a list containing each argument.
  • const: The value to use for a mention of the config item where there is no accompanying argument. This is only ever used when nargs == 0 or nargs == "+".

  • type: The type to which each argument of the config item should be converted. This can be any callable object that takes a single argument (an object with a __call__(self, arg) method), including classes like int and functions that take a single argument. Note that some sources that read typed data may produce config item argument values that aren’t always str objects.

    The default type is str unless that doesn’t make sense (e.g. when nargs == 0.

  • required: specifies whether an exception should be raised if a value for this config item cannot be found in any source.

    The default required is False.

  • choices: specifies a collection of valid values for the arguments of the config item. If choices is specified, an exception is raised if the config item is mentioned in a source with an argument that is not in choices.

add_source(source, *args, **kwargs)

Add a new config source to the ConfigParser.

The only argument required for all sources is the source parameter which may be the name of a source or a class that implements a source. Other arguments are passed on to the class that implements the source.

The built-in sources are:

  • argparse: for getting config values from the command line using an argparse.ArgumentParser.
  • simple_argparse: a simpler version of the argparse source that is easier to use but doesn’t allow you to add any arguments that aren’t also config items.
  • environment: for getting config values from environment variables.
  • json: for getting config values from JSON files.
  • dict: for getting config values from Python dictionaries.

See Sources for more information about the built-in sources and creating your own sources.

Return the created config source object.

parse_config()

Parse the config sources.

Returns: a Namespace object containing the parsed values.

partially_parse_config()

Parse the config sources, but don’t raise a RequiredConfigNotFoundError exception if a required config is not found in any config source.

Returns: a Namespace object containing the parsed values.

class multiconfparse.CountAction(**kwargs)

The count action stores the number of times a config item is mentioned in the config sources. Its behaviour is based on the count argparse action.

Notes about the arguments to ConfigParser.add_config():

  • nargs is not accepted as an argument. nargs is always 0 for count actions.

  • const is not accepted as an argument - it doesn’t make sense for count.

  • required is not accepted as an argument. required is always False for count actions.

  • type is not accepted as an argument - it doesn’t make sense for count.

  • choices is not accepted as an argument - it doesn’t make sense for count.

  • If the default argument is given and is not SUPPRESS, it acts as the initial value for the count. I.e. the final value for the config item will be the number of mentions of the config item in the sources, plus the value of default.

    Note that if the config item is not found in any sources and default is not given, it is not assumed to be 0. The final value for the config item would be None in this case.

Examples:

parser = multiconfparse.ConfigParser()
parser.add_config("config_item1", action="count")
parser.add_source("dict", {"config_item1": None})
parser.add_source("dict", {"config_item1": None})
parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": 2,
# }
parser = multiconfparse.ConfigParser()
parser.add_config("config_item1", action="count", default=10)
parser.add_source("dict", {"config_item1": None})
parser.add_source("dict", {"config_item1": None})
parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": 12,
# }
parser = multiconfparse.ConfigParser()
parser.add_config("config_item1", action="count")
parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": None,
# }
class multiconfparse.DictSource(config_specs, values_dict, none_values=None, priority=0)

Obtains config values from a Python dict object.

Do not create DictSource objects directly, add them to a ConfigParser object using ConfigParser.add_source(). For example:

parser = multiconfparse.ConfigParser()
parser.add_config("config_item1")
parser.add_config("config_item2", nargs=2, type=int)
parser.add_config("config_item3", action="store_true")

values_dict = {
    "config_item1": "v1",
    "config_item2": [1, 2],
    "config_item3": None,
}
parser.add_source("dict", values_dict)
parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": "v1",
#   "config_item2": [1, 2],
#   "config_item3": True,
# }

The arguments of ConfigParser.add_source() for the dict source are:

  • source (required, positional): "dict".

  • values_dict (required, positional): the dict containing the config values.

    Note that:

    • Values in values_dict for config items with nargs == 0 or nargs == "?" (where the const value should be used rather than the value from the dict) should be values from the none_values list described below.

    • Values in values_dict for config items with nargs >= 2, nargs == "+" or nargs == "*" should be list objects with an element for each argument of the config item.

      In the special case where nargs == "+" or nargs == "*" and there is a single argument for the config item, the value may be given without the enclosing list, unless the argument is itself a list.

  • none_values (optional, keyword): a list of values that, when seen in values_dict, should be treated as if they were not present (i.e. values for config items with nargs == 0 or nargs == "?" (where the const value should be used rather than the value from the dict).

    The default none_values is [None, multiconfparse.MENTIONED_WITHOUT_VALUE]. using none_values=[multiconfparse.MENTIONED_WITHOUT_VALUE] is useful if you want None to be treated as a valid config value.

  • priority (optional, keyword): The priority for the source. The default priority for a dict source is 0.

class multiconfparse.EnvironmentSource(config_specs, none_values=None, priority=10, env_var_prefix='')

Obtains config values from the environment.

Do not create EnvironmentSource objects directly, add them to a ConfigParser object using ConfigParser.add_source(). For example:

# For demonstration purposes, set some config values in environment
# variables
os.environ["MY_APP_CONFIG_ITEM1"] = "v1"
os.environ["MY_APP_CONFIG_ITEM2"] = "1 2"
os.environ["MY_APP_CONFIG_ITEM3"] = ""

parser = multiconfparse.ConfigParser()
parser.add_config("config_item1")
parser.add_config("config_item2", nargs=2, type=int)
parser.add_config("config_item3", action="store_true")
parser.add_source("environment", env_var_prefix="MY_APP_")
parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": "v1",
#   "config_item2": [1, 2],
#   "config_item3": True,
# }

The arguments of ConfigParser.add_source() for the environment source are:

  • source (required, positional): "environment"

  • none_values (optional, keyword): a list of values that, when seen in environment variables, should be treated as if they were not present (i.e. values for config items with nargs == 0 or nargs == "?" (where the const value should be used rather than the value from the dict).

    The default none_values is [""]. using a different value for none_values is useful you want the empty string to be treated as a valid config value.

  • priority (optional, keyword): The priority for the source. The default priority for an environment source is 10.

  • env_var_prefix (optional, keyword): a string prefixed to the environment variable names that the source will look for. The default value is "".

Note that:

  • The name of the environment variable for a config item is the config item’s name, converted to upper case, then prefixed with env_var_prefix.
  • Values in environment variables for config items with nargs == 0 or nargs == "?" (where the const value should be used rather than the value from the environment variable) should be values from the none_values list described above.
  • Values in environment variables for config items with nargs >= 2, nargs == "+" or nargs == "*" are split into arguments by shlex.split() (i.e. like arguments given on a command line via a shell). See the shlex documentation for full details.
class multiconfparse.ExtendAction(**kwargs)

The extend action stores the value for each argument of each mention of a config item in a list. The list is sorted according to the priorities of the mentions of the config item, lower priorities first. The Behaviour is based on the extend argparse action, although the behaviour when nargs == None or nargs == "?" is different.

Notes about the arguments to ConfigParser.add_config():

  • nargs == 0 is not allowed. The default nargs value is “+”.

    Unlike the append action, when nargs >= 1, nargs == "+" or nargs == "*", each value in the list for the config item is not itself a list containing the arguments for a mention of the config item. Each argument of each mention is added separately to the list that makes the final value for the config item.

    Unlike the argparse extend action, when nargs == None or nargs == "?", the multiconfparse extend action behaves exactly like the append action.

  • The const argument is only accepted when nargs == "?".

  • The default argument (if it is given and is not SUPPRESS) is used as the initial list of values. This means that the default value is incorporated into the final value for the config item, even if the config item is mentioned in a source.

Example:

parser = multiconfparse.ConfigParser()
parser.add_config(
    "config_item1",
    action="extend",
    default=[["v1", "v2"]]
)
parser.add_source("dict", {"config_item1": ["v3", "v4"]}, priority=2)
parser.add_source("dict", {"config_item1": ["v5"]}, priority=1)
parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": ["v1", "v2", "v5", "v3", "v4"],
# }
exception multiconfparse.InvalidChoiceError(spec, value)

Exception raised when a config value is not from a specified set of values.

exception multiconfparse.InvalidNumberOfValuesError(spec, value)

Exception raised when the number of values supplied for a config item is not valid.

exception multiconfparse.InvalidValueForNargs0Error(value, none_values)

Exception raised when a value recieved for a config item with nargs=0 is not a “none” value.

class multiconfparse.JsonSource(config_specs, path=None, fileobj=None, none_values=None, json_none_values=None, priority=0)

Obtains config values from a JSON file.

Do not create objects of this class directly - create them via ConfigParser.add_source(). For example:

parser = multiconfparse.ConfigParser()
parser.add_config("config_item1")
parser.add_config("config_item2", nargs=2, type=int)
parser.add_config("config_item3", action="store_true")

fileobj = io.StringIO('''
    {
        "config_item1": "v1",
        "config_item2": [1, 2],
        "config_item3": null
    }
''')
parser.add_source("json", fileobj=fileobj)

config_parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": "v1",
#   "config_item2": [1, 2],
#   "config_item3": True,
# }

The arguments of ConfigParser.add_source() for json sources are:

  • source (required, positional): "json".
  • priority (optional, keyword): The priority for the source. The default priority for a json source is 0.
  • path (optional, keyword): path to the JSON file to parse. Exactly one of the path and fileobj options must be given.
  • fileobj (optional keyword): a file object representing a stream of JSON data. Exactly one of the path and fileobj options must be given.
  • none_values (optional, keyword): a list of python values that, when seen as config item values after JSON decoding, should be treated as if they were not present (i.e. values for config items with nargs == 0 or nargs == "?" (where the const value should be used rather than the value from the dict). The default none_values is [].
  • json_none_values (optional, keyword): a list of JSON values (as strings) that are decoded into Python values and added to none_values. The default json_none_values is ["null"].

Notes:

  • The data in the JSON file should be a JSON object. Each config item value should be assigned to a field of the object that has the same name as the config item.

  • Fields in the JSON object for config items with nargs == 0 or nargs == "?" (where the const value should be used rather than the value from the dict) should either have values from the json_none_values list or should decode to values in the none_values list.

  • Fields in the JSON object for config items with nargs >= 2, nargs == "+" or nargs == "*" should be JSON arrays with an element for each argument of the config item.

    In the special case where nargs == "+" or nargs == "*" and there is a single argument for the config item, the value may be given without the enclosing JSON array, unless the argument is itself an array.

multiconfparse.NOT_GIVEN = NOT_GIVEN

Singleton used to represent that an option or config item is not present.

This is used rather than None to distinguish between:

  • the case where the user has provided an option with the value :data:None` and the user has not provided an option at all;
  • the case where a config item has the value None and the case where the config item not been mentioned at all in the config. Contrast this with MENTIONED_WITHOUT_VALUE which represents a config item that has been mentioned in the config but does not have a value (e.g. for a config item with nargs == 0).
class multiconfparse.Namespace

An object to hold values of config items.

Namespace objects are essentially plain objects used as the return values of ConfigParser.parse_config(). Retrieve values with normal attribute accesses:

config_values = parser.parse_config()
config_value = config_values.config_name

To set values (if, for example, you are implementing a Source subclass), use setattr:

ns = multiconfparse.Namespace()
setattr(ns, config_name, config_value)
exception multiconfparse.ParseError

Base class for exceptions indicating a configuration error.

exception multiconfparse.RequiredConfigNotFoundError

Exception raised when a required config value could not be found from any source.

multiconfparse.SUPPRESS = SUPPRESS

Singleton used as a default value for a config item to indicate that if no value is found for the config item in any source, it should not be given an attribute in the Namespace returned by ConfigParser.parse_config(). The default behaviour (when a default value is not given by the user) is for the Namespace returned by ConfigParser.parse_config() to have an attribute with a value of None.

class multiconfparse.SimpleArgparseSource(config_specs, argument_parser_class=<class 'argparse.ArgumentParser'>, priority=20, **kwargs)

Obtains config values from the command line.

The simple_argparse source is simpler to use than the argparse source but it doesn’t allow adding arguments that are not config items.

Do not create objects of this class directly - create them via ConfigParser.add_source() instead. For example:

parser = multiconfparse.ConfigParser()
parser.add_config("config_item1")
parser.add_config("config_item2", nargs=2, type=int)
parser.add_config("config_item3", action="store_true")
parser.add_source("simple_argparse")
config_parser.parse_config()
# If the command line looks something like:
#    PROG_NAME --config-item1 v1 --config-item2 1 2 --config-item-3
# The result would be:
# multiconfparse.Namespace {
#   "config_item1": "v1",
#   "config_item2": [1, 2],
#   "config_item3": True,
# }

The arguments of ConfigParser.add_source() for the simple_argparse source are:

  • source (required, positional): "simple_argparse"
  • argument_parser_class (optional, keyword): a class derived from argparse.ArgumentParser to use instead of ArgumentParser itself. This can be useful if you want to override argparse.ArgumentParser.exit() or argparse.ArgumentParser.error().
  • priority (optional, keyword): The priority for the source. The default priority for a simple_argparse source is 20.
  • Extra keyword arguments to pass to argparse.ArgumentParser. E.g. prog, allow_help. Don’t use the argument_default option though - the simple_argparse sources sets this internally. See the config_default option for ConfigParser instead.

Note that:

  • The name of the command line argument for a config item is the config item’s name with underscores (_) converted to hyphens (-) and prefixed with --.
class multiconfparse.Source(priority=0)

Abstract base for classes that parse config sources.

All config source classes should inherit from Source, have a name class attribute containing the name of the source, and provide an implementation for the parse_config() method.

parse_config()

Read the values of config items for this source.

This is an abstract method that subclasses must implement to return a Namespace object where:

  • The returned Namespace has an attribute for each config item found. The name of the attribute for a config item must be the config item’s name as specified by the name attribute of its Action.

  • The value for each attribute is a list, where each element of the list is a value given for the config item in the source. The elements should be ordered so that values appearing earlier in the source are earlier in the list. In the common case where only a single value for the config item is given in the source, the attribute’s value should be a list with a single element.

    For example, if config_item1 is mentioned in the source once with value "v1" and config_item2 is mentioned in the source twice with values "v2" and then "v3", the returned Namespace object would have an attribute config_item1 with value ["v1"] and an attribute config_item2 with value ["v2", "v3"].

  • If a config item with nargs == 0 or nargs == "?" is mentioned in the source without a value (or possibly with a source-specific value that means None/null for sources where a value must always be given for a config item), the value for that mention of the config item should be given in the list of values as MENTIONED_WITHOUT_VALUE.

  • If a config item with nargs == None, nargs == 1 or nargs == "?" is mentioned in the source with a value, the value for that mention of the config item should be given in the list of values as the value itself.

  • If a config item with nargs >= 2 , nargs == "*" or nargs == "+" is mentioned in the source, the value for that mention of the config item should be given in the list of values as a list of the values/arguments given in that mention.

    For example, if a config item config_item1 with nargs == 2 appears in the source first with values/arguments of "v1a" and "v1b" and then again with values/arguments of "v2a" and "v2b", the config_item1 attribute in the Namespace should have a value of [["v1a", "v1b"], ["v2a", "v2b"]].

  • None of the values returned should yet have been coerced into the types specified by the user in ConfigParser.add_config().

class multiconfparse.StoreAction(const=None, **kwargs)

The store action simply stores the value from the highest priority mention of a config item. Its behaviour is based on the store argparse action and is the default action.

Arguments to ConfigParser.add_config() have standard behaviour, but note:

  • nargs == 0 is not allowed. The default nargs value is None.
  • The const argument is only accepted when nargs == "?".

Examples:

parser = multiconfparse.ConfigParser()
parser.add_config("config_item1")
parser.add_source("dict", {"config_item1": "v1"}, priority=2)
parser.add_source("dict", {"config_item1": "v2"}, priority=1)
parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": "v1",
# }
parser = multiconfparse.ConfigParser()
parser.add_config("config_item1", nargs=2, type=int, default=[1, 2])
parser.add_source("simple_argparse")
parser.parse_config()
#
# If the command line looks something like:
#   prog some-arg --config-item1 3 4
# parse_config() will return something like:
#   multiconfparse.Namespace {
#       "config_item1": [3, 4],
#   }
#
# If the command line looks something like:
#   prog some-arg
# parse_config() will return something like:
#   multiconfparse.Namespace {
#       "config_item1": [1, 2],
#   }
class multiconfparse.StoreConstAction(const, **kwargs)

The store_const action stores the value from the const argument whenever a config item is mentioned in a source. Its behaviour is based on the store_const argparse action.

Notes about the arguments to ConfigParser.add_config():

  • The const argument is mandatory.
  • nargs is not accepted as an argument. nargs is always 0 for store_const actions.
  • required is not accepted as an argument. required is always False for store_const actions.
  • type is not accepted as an argument - it doesn’t make sense for store_const.
  • choices is not accepted as an argument - it doesn’t make sense for store_const.

Example:

parser = multiconfparse.ConfigParser()
parser.add_config(
    "config_item1",
    action="store_const",
    const="yes",
    default="no"
)
parser.add_source("dict", {"config_item1": None})
parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": "yes",
# }
class multiconfparse.StoreFalseAction(default=True, **kwargs)

The store_false action simply stores the value False whenever a config item is mentioned in a source. Its behaviour is based on the store_false argparse action.

Notes about the arguments to ConfigParser.add_config():

  • const is not accepted as an argument - const is always False for store_false actions.
  • nargs is not accepted as an argument. nargs is always 0 for store_false actions.
  • required is not accepted as an argument. required is always False for store_false actions.
  • type is not accepted as an argument - it doesn’t make sense for store_false.
  • choices is not accepted as an argument - it doesn’t make sense for store_false.
  • The default value for the default argument is True.

Examples:

parser = multiconfparse.ConfigParser()
parser.add_config("config_item1", action="store_false")
parser.add_source("dict", {"config_item1": None})
parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": False,
# }
parser = multiconfparse.ConfigParser()
parser.add_config("config_item1", action="store_false")
parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": True,
# }
class multiconfparse.StoreTrueAction(default=False, **kwargs)

The store_true action simply stores the value True whenever a config item is mentioned in a source. Its behaviour is based on the store_true argparse action.

Notes about the arguments to ConfigParser.add_config():

  • const is not accepted as an argument - const is always True for store_true actions.
  • nargs is not accepted as an argument. nargs is always 0 for store_true actions.
  • required is not accepted as an argument. required is always False for store_true actions.
  • type is not accepted as an argument - it doesn’t make sense for store_true.
  • choices is not accepted as an argument - it doesn’t make sense for store_true.
  • The default value for the default argument is False.

Examples:

parser = multiconfparse.ConfigParser()
parser.add_config("config_item1", action="store_true")
parser.add_source("dict", {"config_item1": None})
parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": True,
# }
parser = multiconfparse.ConfigParser()
parser.add_config("config_item1", action="store_true")
parser.parse_config()
# -> multiconfparse.Namespace {
#   "config_item1": False,
# }