def _check_value_key(action:Action, value:Any, key:str, cfg) -> Any: """Checks the value for a given action. Args: action: The action used for parsing. value: The value to parse. key: The configuration key. Raises: TypeError: If the value is not valid. """ if action.choices is not None and isinstance(action, _ActionSubCommands): if key == action.dest: return value parser = action._name_parser_map[key] parser.check_config(value) # type: ignore elif hasattr(action, '_check_type'): value = action._check_type(value, cfg=cfg) # type: ignore elif action.type is not None: try: if action.nargs in {None, '?'} or action.nargs == 0: value = action.type(value) elif value is not None: for k, v in enumerate(value): value[k] = action.type(v) except (TypeError, ValueError) as ex: raise TypeError('Parser key "'+str(key)+'": '+str(ex)) from ex return value
def get_default(action: argparse.Action, section: Dict, key: Text) -> Any: """ Find default value for an option. This will only be used if an argument is not specified at the command line. The defaults will be found in this order (from lowest to highest): 1. argparse default 3. ini file 3. environment variable """ default = action.default env = get_env(key) # environment has higher presedence than config section if key in env: default = env[key] elif key in section: default = section[key] # if not env or section, keep default from argparse # parse true/yes as True and false/no as False for # action="store_true" and action="store_false" if action.const in (True, False) and isinstance(default, str): if default.lower() in ("true", "yes"): default = True elif default.lower() in ("false", "no"): default = False if action.nargs in (argparse.ZERO_OR_MORE, argparse.ONE_OR_MORE): if isinstance(default, str): default = default.split() elif isinstance(default, list): pass else: raise ValueError("Not string or list in nargs") # If argument type is set and default is not None, enforce type # Eg, for this argument specification # parser.add_argument('--int-arg', type=int) # --int-arg 2 # will give you int(2) # If --int-arg is omitted, it will use None if action.type is not None and default is not None: default = action.type(default) return default