Actions¶
The built-in actions are:
store¶
-
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], # }
store_const¶
-
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
store_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, # }
store_false¶
-
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, # }
append¶
-
class
multiconfparse.AppendAction(const=None, default=NOT_GIVEN, **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"], # }
count¶
-
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, # }
extend¶
-
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"], # }
Creating your own action classes¶
To create your own action class, create a subclass of Action:
-
class
multiconfparse.Action(name, dest=None, 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
__call__()method documented below.Have an
action_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;dest;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=None, 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__().
-
__call__(namespace, args) Combine the arguments from a mention of this config with any existing value.
This method is called once for each mention of the config item in the sources in order to combine the arguments from the mention with any existing value.
namespacewill be the sameNamespaceobject for all calls to this function during aConfigParser.parse_config()call, and it is used to hold the so-far-accumulated value for the config item mentions.This method’s purpose is to combine the current value for this config item in
namespacewith the values in thenewargument, and write the combined value into back intonamespace.The first time this method is called, if the config item has a default value,
namespacewill have an attribute for the config item and it will contain the default value; otherwisenamespacewill not have an attribute for the config item.After the first call to this method,
namespaceshould have an attribute value for the config item set by the previous call.Notes:
- The name of the attribute in
namespacefor this config item is given by this object’sdestattribute. - The calls to this method are made in order of the priorities of the config item mentions in the sources, lowest priority first.
- The values in
newhave already been coerced to the config item’stype. - The values in
newhave already been checked forchoicesvalidity. - The number of values in
newhas already been checked fornargsvalidity. - If no arguments for the config item were given,
newwill just be an emptylist.
For example, the
__call__()method for theappendaction is:def __call__(self, namespace, args): current = getattr(namespace, self.dest, []) if self.nargs == "?" and not args: current.append(self.const) elif self.nargs is None or self.nargs == "?": assert len(args) == 1 current.extend(args) else: current.append(args) setattr(namespace, self.dest, current)
- The name of the attribute in
The full example of the class for the
store_constaction is:class StoreConstAction(Action): action_name = "store_const" def __init__(self, const, **kwargs): super().__init__( nargs=0, type=None, required=False, choices=None, **kwargs, ) self.const = const def __call__(self, namespace, args): assert not args setattr(namespace, self.dest, self.const)