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 beNOT_GIVENorMENTIONED_WITHOUT_VALUE).new: The new value (which will never beNOT_GIVENbut may beMENTIONED_WITHOUT_VALUE) to combine with the current value for the config item.
The
currentandnewwill have:- been coerced to the config item’s
type; - been checked for
nargsandchoicesvalidity; - had values for
nargs == 1converted to a single elementlist.
Returns: the new combined value, which must not be
NOT_GIVEN.
For example, the
accumulate_processed_value()method for theappendaction 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
nameclass attribute set to the name of the action that the class implements.Have an
__init__()method that accepts arguments passed toConfigParser.add_config()calls by the user (except theactionargument) and which callsAction.__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
Actionobject 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**kwargsargument to collect any arguments that are not used or modified by the action class, then passing that**kwargsargument toAction.__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, thestore_constaction 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, orchoicesarguments when adding astore_constaction because if the user specifies those arguments they will be given twice in the call toAction.__init__().
The full example of the class for the
store_constaction 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 beNOT_GIVENorMENTIONED_WITHOUT_VALUE).new: The new value (which will never beNOT_GIVENbut may beMENTIONED_WITHOUT_VALUE) to combine with the current value for the config item.
The
currentandnewwill have:- been coerced to the config item’s
type; - been checked for
nargsandchoicesvalidity; - had values for
nargs == 1converted to a single elementlist.
Returns: the new combined value, which must not be
NOT_GIVEN.
-
class
multiconfparse.AppendAction(const=None, **kwargs)¶ The
appendaction stores the value for each mention of a config item in alist. Thelistis sorted according to the priorities of the mentions of the config item, lower priorities first. The Behaviour is based on theappendargparseaction.Notes about the arguments to
ConfigParser.add_config():nargs == 0is not allowed. The defaultnargsvalue isNone.When
nargs >= 1,nargs == "+"ornargs == "*", each value in thelistfor the config item is itself alistcontaining the arguments for a mention of the config item.The
constargument is only accepted whennargs == "?".The
defaultargument (if it is given and is notSUPPRESS) is used as the initiallistof values. This means that thedefaultvalue 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
ArgparseSourceobjects directly, add them to aConfigParserobject usingConfigParser.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
argparsesource does not create anargparse.ArgumentParserfor you. This is to allow extra command line arguments to be added to anargparse.ArgumentParserthat are not config items. InsteadArgparseSource, which implements theargparsesource provides two methods to provide communication with theargparse.ArgumentParser:-
add_configs_to_argparse_parser(argparse_parser) Add arguments to an
argparse.ArgumentParserfor config items.
-
notify_parsed_args(argparse_namespace) Notify the
argparsesource of theargparse.Namespaceobject returned byargparse.ArgumentParser.parse_args().
If you don’t need to add command line arguments other than for config items, see
SimpleArgparseSourcewhich implements thesimple_argparsesource.The arguments of
ConfigParser.add_source()for theargparsesource are:source(required, positional):"argparse"priority(optional, keyword): The priority for the source. The default priority for anargparsesource is20.
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.ArgumentParserfor config items.
-
notify_parsed_args(argparse_namespace)¶ Notify the
argparsesource of theargparse.Namespaceobject returned byargparse.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 theNamespacereturned byparse_config()for config items for which no value was found.The default behaviour (when
config_defaultisNOT_GIVEN) is to represent these config items with the valueNone.Set
config_defaulttoSUPPRESSto prevent these configs from having an attribute set in theNamespaceat 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
Namespaceobject returned byparse_config(), the name of the attribute used for this config item will benameand must be a valid Python identifier.nameis 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 ofname, however. For example, theargparseandsimple_argparsesources will convert underscores (_) to hyphens (-) and add a--prefix, so if a config item had the name"config_item1", theargparseandsimple_argparsesources 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 onargparseactions so theargparse documentationmay also provide useful information.store: this action just stores the highest priority value for config item.store_const: this stores the value specified in theconstargument.store_true: this stores the valueTrueand sets thedefaultargument toFalse. It is a special case ofstore_const.store_false: this stores the valueFalseand sets thedefaultargument toTrue. It is a special case ofstore_const.append: this creates alistcontaining every value seen (with lower priority values first). Whennargs >= 1,nargs == "+"ornargs == "*", 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 alistcontaining every value seen (with lower priority values first). Unlikeappend, whennargs >= 1,nargs == "+"ornargs == "*", 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 thedefaultvalue into the final value for the config item even if the config item is mentioned in one of the sources (e.g.append,countandextend).Note that the default value for all config items can also be set by passing a value for the
config_defaultargument ofConfigParser. If both theconfig_defaultargument toConfigParserand thedefaultargument toadd_config()are used then only thedefaultargument toadd_config()is used.If a default value is not provided for the config item by the
defaultargument, theconfig_defaultargument or by the action class (like e.g. store_true does), then the final value for the config will beNoneif the config item is not mentioned in any source.The special value
SUPPRESScan be passed as thedefaultargument. In this case, if the config item is not mentioned in any source, it will not be given an attribute in theNamespaceobject returned byparse_config().exclude_sources(optional, keyword): a collection of source names orSourceclasses that should ignore this config item. This argument is mutually exclusive withinclude_sources. If neitherexclude_sourcesnorinclude_sourcesis given, the config item will be looked for by all sources added to theConfigParser.include_sources(optional, keyword): a collection of source names orSourceclasses that should look for this config item. This argument is mutually exclusive withexclude_sources. If neitherexclude_sourcesnorinclude_sourcesis given, the config item will be looked for by all sources added to theConfigParser.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 thatnargscan 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 toadd_config()but may be implicit for an action (e.g.store_constorcount).- An
intN >= 1: the config item will takeNarguments and the value for a mention of the config item will be alistcontaining each argument. In particular, whennargs == 1the value for each mention of a config item will be alistcontaining 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’sconstargument."*": The config item will take zero or more arguments and the value for a mention of the config item will be alistcontaining each argument."+"The config item will take one or more arguments and the value for a mention of the config item will be alistcontaining 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 whennargs == 0ornargs == "+".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 likeintand functions that take a single argument. Note that some sources that read typed data may produce config item argument values that aren’t alwaysstrobjects.The default
typeisstrunless that doesn’t make sense (e.g. whennargs == 0.required: specifies whether an exception should be raised if a value for this config item cannot be found in any source.The default
requiredisFalse.choices: specifies a collection of valid values for the arguments of the config item. Ifchoicesis specified, an exception is raised if the config item is mentioned in a source with an argument that is not inchoices.
-
add_source(source, *args, **kwargs)¶ Add a new config source to the
ConfigParser.The only argument required for all sources is the
sourceparameter 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 anargparse.ArgumentParser.simple_argparse: a simpler version of theargparsesource 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.
-
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
countaction stores the number of times a config item is mentioned in the config sources. Its behaviour is based on thecountargparseaction.Notes about the arguments to
ConfigParser.add_config():nargsis not accepted as an argument.nargsis always0forcountactions.constis not accepted as an argument - it doesn’t make sense forcount.requiredis not accepted as an argument.requiredis alwaysFalseforcountactions.typeis not accepted as an argument - it doesn’t make sense forcount.choicesis not accepted as an argument - it doesn’t make sense forcount.If the
defaultargument is given and is notSUPPRESS, 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 ofdefault.Note that if the config item is not found in any sources and
defaultis not given, it is not assumed to be0. The final value for the config item would beNonein 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
dictobject.Do not create
DictSourceobjects directly, add them to aConfigParserobject usingConfigParser.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 thedictsource are:source(required, positional):"dict".values_dict(required, positional): thedictcontaining the config values.Note that:
Values in
values_dictfor config items withnargs == 0ornargs == "?"(where theconstvalue should be used rather than the value from the dict) should be values from thenone_valueslist described below.Values in
values_dictfor config items withnargs >= 2,nargs == "+"ornargs == "*"should belistobjects with an element for each argument of the config item.In the special case where
nargs == "+"ornargs == "*"and there is a single argument for the config item, the value may be given without the enclosinglist, unless the argument is itself alist.
none_values(optional, keyword): a list of values that, when seen invalues_dict, should be treated as if they were not present (i.e. values for config items withnargs == 0ornargs == "?"(where theconstvalue should be used rather than the value from the dict).The default
none_valuesis[None, multiconfparse.MENTIONED_WITHOUT_VALUE]. usingnone_values=[multiconfparse.MENTIONED_WITHOUT_VALUE]is useful if you wantNoneto be treated as a valid config value.priority(optional, keyword): The priority for the source. The default priority for adictsource is0.
-
class
multiconfparse.EnvironmentSource(config_specs, none_values=None, priority=10, env_var_prefix='')¶ Obtains config values from the environment.
Do not create
EnvironmentSourceobjects directly, add them to aConfigParserobject usingConfigParser.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 theenvironmentsource 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 withnargs == 0ornargs == "?"(where theconstvalue should be used rather than the value from the dict).The default
none_valuesis[""]. using a different value fornone_valuesis 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 anenvironmentsource is10.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 == 0ornargs == "?"(where theconstvalue should be used rather than the value from the environment variable) should be values from thenone_valueslist described above. - Values in environment variables for config items with
nargs >= 2,nargs == "+"ornargs == "*"are split into arguments byshlex.split()(i.e. like arguments given on a command line via a shell). See theshlexdocumentation for full details.
-
class
multiconfparse.ExtendAction(**kwargs)¶ The
extendaction stores the value for each argument of each mention of a config item in alist. Thelistis sorted according to the priorities of the mentions of the config item, lower priorities first. The Behaviour is based on theextendargparseaction, although the behaviour whennargs == Noneornargs == "?"is different.Notes about the arguments to
ConfigParser.add_config():nargs == 0is not allowed. The defaultnargsvalue is “+”.Unlike the
appendaction, whennargs >= 1,nargs == "+"ornargs == "*", each value in thelistfor the config item is not itself alistcontaining the arguments for a mention of the config item. Each argument of each mention is added separately to thelistthat makes the final value for the config item.Unlike the
argparseextendaction, whennargs == Noneornargs == "?", themulticonfparseextendaction behaves exactly like theappendaction.The
constargument is only accepted whennargs == "?".The
defaultargument (if it is given and is notSUPPRESS) is used as the initiallistof values. This means that thedefaultvalue 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()forjsonsources are:source(required, positional):"json".priority(optional, keyword): The priority for the source. The default priority for ajsonsource is0.path(optional, keyword): path to the JSON file to parse. Exactly one of thepathandfileobjoptions must be given.fileobj(optional keyword): a file object representing a stream of JSON data. Exactly one of thepathandfileobjoptions 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 withnargs == 0ornargs == "?"(where theconstvalue should be used rather than the value from the dict). The defaultnone_valuesis[].json_none_values(optional, keyword): a list of JSON values (as strings) that are decoded into Python values and added tonone_values. The defaultjson_none_valuesis["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 == 0ornargs == "?"(where theconstvalue should be used rather than the value from the dict) should either have values from thejson_none_valueslist or should decode to values in thenone_valueslist.Fields in the JSON object for config items with
nargs >= 2,nargs == "+"ornargs == "*"should be JSON arrays with an element for each argument of the config item.In the special case where
nargs == "+"ornargs == "*"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
Noneto 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
Noneand the case where the config item not been mentioned at all in the config. Contrast this withMENTIONED_WITHOUT_VALUEwhich represents a config item that has been mentioned in the config but does not have a value (e.g. for a config item withnargs == 0).
-
class
multiconfparse.Namespace¶ An object to hold values of config items.
Namespaceobjects are essentially plain objects used as the return values ofConfigParser.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
Sourcesubclass), usesetattr: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
defaultvalue 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 theNamespacereturned byConfigParser.parse_config(). The default behaviour (when adefaultvalue is not given by the user) is for theNamespacereturned byConfigParser.parse_config()to have an attribute with a value ofNone.
-
class
multiconfparse.SimpleArgparseSource(config_specs, argument_parser_class=<class 'argparse.ArgumentParser'>, priority=20, **kwargs)¶ Obtains config values from the command line.
The
simple_argparsesource is simpler to use than theargparsesource 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 thesimple_argparsesource are:source(required, positional):"simple_argparse"argument_parser_class(optional, keyword): a class derived fromargparse.ArgumentParserto use instead ofArgumentParseritself. This can be useful if you want to overrideargparse.ArgumentParser.exit()orargparse.ArgumentParser.error().priority(optional, keyword): The priority for the source. The default priority for asimple_argparsesource is20.- Extra keyword arguments to pass to
argparse.ArgumentParser. E.g.prog,allow_help. Don’t use theargument_defaultoption though - thesimple_argparsesources sets this internally. See theconfig_defaultoption forConfigParserinstead.
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 anameclass attribute containing the name of the source, and provide an implementation for theparse_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
Namespaceobject where:The returned
Namespacehas an attribute for each config item found. The name of the attribute for a config item must be the config item’snameas specified by thenameattribute of itsAction.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_item1is mentioned in the source once with value"v1"andconfig_item2is mentioned in the source twice with values"v2"and then"v3", the returnedNamespaceobject would have an attributeconfig_item1with value["v1"]and an attributeconfig_item2with value["v2", "v3"].If a config item with
nargs == 0ornargs == "?"is mentioned in the source without a value (or possibly with a source-specific value that meansNone/nullfor 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 asMENTIONED_WITHOUT_VALUE.If a config item with
nargs == None,nargs == 1ornargs == "?"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 == "*"ornargs == "+"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_item1withnargs == 2appears in the source first with values/arguments of"v1a"and"v1b"and then again with values/arguments of"v2a"and"v2b", theconfig_item1attribute in theNamespaceshould 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
storeaction simply stores the value from the highest priority mention of a config item. Its behaviour is based on thestoreargparseaction and is the default action.Arguments to
ConfigParser.add_config()have standard behaviour, but note:nargs == 0is not allowed. The defaultnargsvalue isNone.- The
constargument is only accepted whennargs == "?".
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_constaction stores the value from theconstargument whenever a config item is mentioned in a source. Its behaviour is based on thestore_constargparseaction.Notes about the arguments to
ConfigParser.add_config():- The
constargument is mandatory. nargsis not accepted as an argument.nargsis always0forstore_constactions.requiredis not accepted as an argument.requiredis alwaysFalseforstore_constactions.typeis not accepted as an argument - it doesn’t make sense forstore_const.choicesis not accepted as an argument - it doesn’t make sense forstore_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", # }
- The
-
class
multiconfparse.StoreFalseAction(default=True, **kwargs)¶ The
store_falseaction simply stores the valueFalsewhenever a config item is mentioned in a source. Its behaviour is based on thestore_falseargparseaction.Notes about the arguments to
ConfigParser.add_config():constis not accepted as an argument -constis alwaysFalseforstore_falseactions.nargsis not accepted as an argument.nargsis always0forstore_falseactions.requiredis not accepted as an argument.requiredis alwaysFalseforstore_falseactions.typeis not accepted as an argument - it doesn’t make sense forstore_false.choicesis not accepted as an argument - it doesn’t make sense forstore_false.- The default value for the
defaultargument isTrue.
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_trueaction simply stores the valueTruewhenever a config item is mentioned in a source. Its behaviour is based on thestore_trueargparseaction.Notes about the arguments to
ConfigParser.add_config():constis not accepted as an argument -constis alwaysTrueforstore_trueactions.nargsis not accepted as an argument.nargsis always0forstore_trueactions.requiredis not accepted as an argument.requiredis alwaysFalseforstore_trueactions.typeis not accepted as an argument - it doesn’t make sense forstore_true.choicesis not accepted as an argument - it doesn’t make sense forstore_true.- The default value for the
defaultargument isFalse.
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, # }