Actions

The built-in actions are:

store

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],
#   }

store_const

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",
# }

store_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,
# }

store_false

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,
# }

append

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"],
# }

count

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,
# }

extend

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"],
# }

Creating your own action classes

To create your own action class, create a subclass of Action:

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