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_GIVEN
orMENTIONED_WITHOUT_VALUE
).new
: The new value (which will never beNOT_GIVEN
but may beMENTIONED_WITHOUT_VALUE
) to combine with the current value for the config item.
The
current
andnew
will have:- been coerced to the config item’s
type
; - been checked for
nargs
andchoices
validity; - had values for
nargs == 1
converted to a single elementlist
.
Returns: the new combined value, which must not be
NOT_GIVEN
.
For example, the
accumulate_processed_value()
method for theappend
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 toConfigParser.add_config()
calls by the user (except theaction
argument) 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
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 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_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
, orchoices
arguments when adding astore_const
action 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_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 beNOT_GIVEN
orMENTIONED_WITHOUT_VALUE
).new
: The new value (which will never beNOT_GIVEN
but may beMENTIONED_WITHOUT_VALUE
) to combine with the current value for the config item.
The
current
andnew
will have:- been coerced to the config item’s
type
; - been checked for
nargs
andchoices
validity; - had values for
nargs == 1
converted to a single elementlist
.
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 alist
. Thelist
is sorted according to the priorities of the mentions of the config item, lower priorities first. The Behaviour is based on theappend
argparse
action.Notes about the arguments to
ConfigParser.add_config()
:nargs == 0
is not allowed. The defaultnargs
value isNone
.When
nargs >= 1
,nargs == "+"
ornargs == "*"
, each value in thelist
for the config item is itself alist
containing the arguments for a mention of the config item.The
const
argument is only accepted whennargs == "?"
.The
default
argument (if it is given and is notSUPPRESS
) is used as the initiallist
of values. This means that thedefault
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 aConfigParser
object 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
argparse
source does not create anargparse.ArgumentParser
for you. This is to allow extra command line arguments to be added to anargparse.ArgumentParser
that are not config items. InsteadArgparseSource
, which implements theargparse
source provides two methods to provide communication with theargparse.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 theargparse.Namespace
object returned byargparse.ArgumentParser.parse_args()
.
If you don’t need to add command line arguments other than for config items, see
SimpleArgparseSource
which implements thesimple_argparse
source.The arguments of
ConfigParser.add_source()
for theargparse
source are:source
(required, positional):"argparse"
priority
(optional, keyword): The priority for the source. The default priority for anargparse
source 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.ArgumentParser
for config items.
-
notify_parsed_args
(argparse_namespace)¶ Notify the
argparse
source of theargparse.Namespace
object 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 theNamespace
returned byparse_config()
for config items for which no value was found.The default behaviour (when
config_default
isNOT_GIVEN
) is to represent these config items with the valueNone
.Set
config_default
toSUPPRESS
to prevent these configs from having an attribute set in theNamespace
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 byparse_config()
, the name of the attribute used for this config item will bename
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 ofname
, however. For example, theargparse
andsimple_argparse
sources will convert underscores (_
) to hyphens (-
) and add a--
prefix, so if a config item had the name"config_item1"
, theargparse
andsimple_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 onargparse
actions so theargparse 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 theconst
argument.store_true
: this stores the valueTrue
and sets thedefault
argument toFalse
. It is a special case ofstore_const
.store_false
: this stores the valueFalse
and sets thedefault
argument toTrue
. It is a special case ofstore_const
.append
: this creates alist
containing 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 alist
containing 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 thedefault
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
andextend
).Note that the default value for all config items can also be set by passing a value for the
config_default
argument ofConfigParser
. If both theconfig_default
argument toConfigParser
and thedefault
argument toadd_config()
are used then only thedefault
argument toadd_config()
is used.If a default value is not provided for the config item by the
default
argument, theconfig_default
argument or by the action class (like e.g. store_true does), then the final value for the config will beNone
if the config item is not mentioned in any source.The special value
SUPPRESS
can be passed as thedefault
argument. In this case, if the config item is not mentioned in any source, it will not be given an attribute in theNamespace
object returned byparse_config()
.exclude_sources
(optional, keyword): a collection of source names orSource
classes that should ignore this config item. This argument is mutually exclusive withinclude_sources
. If neitherexclude_sources
norinclude_sources
is given, the config item will be looked for by all sources added to theConfigParser
.include_sources
(optional, keyword): a collection of source names orSource
classes that should look for this config item. This argument is mutually exclusive withexclude_sources
. If neitherexclude_sources
norinclude_sources
is 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 thatnargs
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 toadd_config()
but may be implicit for an action (e.g.store_const
orcount
).- An
int
N >= 1
: the config item will takeN
arguments and the value for a mention of the config item will be alist
containing each argument. In particular, whennargs == 1
the value for each mention of a config item will be alist
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’sconst
argument."*"
: The config item will take zero or more arguments and the value for a mention of the config item will be alist
containing each argument."+"
The config item will take one or more arguments and the value for a mention of the config item will be alist
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 whennargs == 0
ornargs == "+"
.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 likeint
and functions that take a single argument. Note that some sources that read typed data may produce config item argument values that aren’t alwaysstr
objects.The default
type
isstr
unless 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
required
isFalse
.choices
: specifies a collection of valid values for the arguments of the config item. Ifchoices
is 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
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 anargparse.ArgumentParser
.simple_argparse
: a simpler version of theargparse
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.
-
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 thecount
argparse
action.Notes about the arguments to
ConfigParser.add_config()
:nargs
is not accepted as an argument.nargs
is always0
forcount
actions.const
is not accepted as an argument - it doesn’t make sense forcount
.required
is not accepted as an argument.required
is alwaysFalse
forcount
actions.type
is not accepted as an argument - it doesn’t make sense forcount
.choices
is not accepted as an argument - it doesn’t make sense forcount
.If the
default
argument 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
default
is not given, it is not assumed to be0
. The final value for the config item would beNone
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 aConfigParser
object 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 thedict
source are:source
(required, positional):"dict"
.values_dict
(required, positional): thedict
containing the config values.Note that:
Values in
values_dict
for config items withnargs == 0
ornargs == "?"
(where theconst
value should be used rather than the value from the dict) should be values from thenone_values
list described below.Values in
values_dict
for config items withnargs >= 2
,nargs == "+"
ornargs == "*"
should belist
objects 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 == 0
ornargs == "?"
(where theconst
value should be used rather than the value from the dict).The default
none_values
is[None, multiconfparse.MENTIONED_WITHOUT_VALUE]
. usingnone_values=[multiconfparse.MENTIONED_WITHOUT_VALUE]
is useful if you wantNone
to be treated as a valid config value.priority
(optional, keyword): The priority for the source. The default priority for adict
source is0
.
-
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 aConfigParser
object 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 theenvironment
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 withnargs == 0
ornargs == "?"
(where theconst
value should be used rather than the value from the dict).The default
none_values
is[""]
. using a different value fornone_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 anenvironment
source 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 == 0
ornargs == "?"
(where theconst
value should be used rather than the value from the environment variable) should be values from thenone_values
list 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 theshlex
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 alist
. Thelist
is sorted according to the priorities of the mentions of the config item, lower priorities first. The Behaviour is based on theextend
argparse
action, although the behaviour whennargs == None
ornargs == "?"
is different.Notes about the arguments to
ConfigParser.add_config()
:nargs == 0
is not allowed. The defaultnargs
value is “+”.Unlike the
append
action, whennargs >= 1
,nargs == "+"
ornargs == "*"
, each value in thelist
for the config item is not itself alist
containing the arguments for a mention of the config item. Each argument of each mention is added separately to thelist
that makes the final value for the config item.Unlike the
argparse
extend
action, whennargs == None
ornargs == "?"
, themulticonfparse
extend
action behaves exactly like theappend
action.The
const
argument is only accepted whennargs == "?"
.The
default
argument (if it is given and is notSUPPRESS
) is used as the initiallist
of values. This means that thedefault
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()
forjson
sources are:source
(required, positional):"json"
.priority
(optional, keyword): The priority for the source. The default priority for ajson
source is0
.path
(optional, keyword): path to the JSON file to parse. Exactly one of thepath
andfileobj
options must be given.fileobj
(optional keyword): a file object representing a stream of JSON data. Exactly one of thepath
andfileobj
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 withnargs == 0
ornargs == "?"
(where theconst
value should be used rather than the value from the dict). The defaultnone_values
is[]
.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_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
ornargs == "?"
(where theconst
value should be used rather than the value from the dict) should either have values from thejson_none_values
list or should decode to values in thenone_values
list.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
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 withMENTIONED_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 withnargs == 0
).
-
class
multiconfparse.
Namespace
¶ An object to hold values of config items.
Namespace
objects 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
Source
subclass), 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
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 theNamespace
returned byConfigParser.parse_config()
. The default behaviour (when adefault
value is not given by the user) is for theNamespace
returned 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_argparse
source is simpler to use than theargparse
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 thesimple_argparse
source are:source
(required, positional):"simple_argparse"
argument_parser_class
(optional, keyword): a class derived fromargparse.ArgumentParser
to use instead ofArgumentParser
itself. 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_argparse
source is20
.- Extra keyword arguments to pass to
argparse.ArgumentParser
. E.g.prog
,allow_help
. Don’t use theargument_default
option though - thesimple_argparse
sources sets this internally. See theconfig_default
option forConfigParser
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 aname
class 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
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’sname
as specified by thename
attribute 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_item1
is mentioned in the source once with value"v1"
andconfig_item2
is mentioned in the source twice with values"v2"
and then"v3"
, the returnedNamespace
object would have an attributeconfig_item1
with value["v1"]
and an attributeconfig_item2
with value["v2", "v3"]
.If a config item with
nargs == 0
ornargs == "?"
is mentioned in the source without a value (or possibly with a source-specific value that meansNone
/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 asMENTIONED_WITHOUT_VALUE
.If a config item with
nargs == None
,nargs == 1
ornargs == "?"
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_item1
withnargs == 2
appears in the source first with values/arguments of"v1a"
and"v1b"
and then again with values/arguments of"v2a"
and"v2b"
, theconfig_item1
attribute in theNamespace
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 thestore
argparse
action and is the default action.Arguments to
ConfigParser.add_config()
have standard behaviour, but note:nargs == 0
is not allowed. The defaultnargs
value isNone
.- The
const
argument 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_const
action stores the value from theconst
argument whenever a config item is mentioned in a source. Its behaviour is based on thestore_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 always0
forstore_const
actions.required
is not accepted as an argument.required
is alwaysFalse
forstore_const
actions.type
is not accepted as an argument - it doesn’t make sense forstore_const
.choices
is 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_false
action simply stores the valueFalse
whenever a config item is mentioned in a source. Its behaviour is based on thestore_false
argparse
action.Notes about the arguments to
ConfigParser.add_config()
:const
is not accepted as an argument -const
is alwaysFalse
forstore_false
actions.nargs
is not accepted as an argument.nargs
is always0
forstore_false
actions.required
is not accepted as an argument.required
is alwaysFalse
forstore_false
actions.type
is not accepted as an argument - it doesn’t make sense forstore_false
.choices
is not accepted as an argument - it doesn’t make sense forstore_false
.- The default value for the
default
argument 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_true
action simply stores the valueTrue
whenever a config item is mentioned in a source. Its behaviour is based on thestore_true
argparse
action.Notes about the arguments to
ConfigParser.add_config()
:const
is not accepted as an argument -const
is alwaysTrue
forstore_true
actions.nargs
is not accepted as an argument.nargs
is always0
forstore_true
actions.required
is not accepted as an argument.required
is alwaysFalse
forstore_true
actions.type
is not accepted as an argument - it doesn’t make sense forstore_true
.choices
is not accepted as an argument - it doesn’t make sense forstore_true
.- The default value for the
default
argument 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, # }