Skip to content

Commit 445dd2e

Browse files
authored
Better input validation and error messages (#349)
* Add input validation to ArgumentParser.__init__ * Fix config_file_parser_class validation to accept instances * Fix black formatting
1 parent 1f18f5c commit 445dd2e

1 file changed

Lines changed: 43 additions & 2 deletions

File tree

configargparse.py

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -911,19 +911,60 @@ def __init__(self, *args, **kwargs):
911911
"given path, then exits",
912912
)
913913

914-
self._config_file_open_func = kwargs.pop("config_file_open_func", open)
914+
config_file_open_func = kwargs.pop("config_file_open_func", open)
915+
916+
# Validate args before proceeding
917+
for name, value in [
918+
("default_config_files", default_config_files),
919+
("args_for_setting_config_path", args_for_setting_config_path),
920+
("args_for_writing_out_config_file", args_for_writing_out_config_file),
921+
]:
922+
if not isinstance(value, (list, tuple)):
923+
hint = " (e.g. ['%s'])" % value if isinstance(value, str) else ""
924+
raise TypeError("%s must be a list%s. Got: %r" % (name, hint, value))
925+
926+
if not callable(config_file_open_func):
927+
raise TypeError(
928+
"config_file_open_func must be callable. Got: %r"
929+
% (config_file_open_func,)
930+
)
931+
932+
self._config_file_open_func = config_file_open_func
915933

916934
self._add_config_file_help = add_config_file_help
917935
self._add_env_var_help = add_env_var_help
918936
self._auto_env_var_prefix = auto_env_var_prefix
919937

938+
if "formatter_class" in kwargs:
939+
fc = kwargs["formatter_class"]
940+
if isinstance(fc, type) and not issubclass(fc, argparse.HelpFormatter):
941+
msg = (
942+
"formatter_class must be a subclass of "
943+
"argparse.HelpFormatter. Got: %r." % (fc,)
944+
)
945+
if issubclass(fc, ConfigFileParser):
946+
msg += " Perhaps you meant to use config_file_parser_class?"
947+
raise TypeError(msg)
948+
920949
argparse.ArgumentParser.__init__(self, *args, **kwargs)
921950

922951
# parse the additional args
923952
if config_file_parser_class is None:
924953
self._config_file_parser = DefaultConfigFileParser()
925-
else:
954+
elif isinstance(config_file_parser_class, ConfigFileParser):
955+
self._config_file_parser = config_file_parser_class
956+
elif isinstance(config_file_parser_class, type) and issubclass(
957+
config_file_parser_class, ConfigFileParser
958+
):
926959
self._config_file_parser = config_file_parser_class()
960+
else:
961+
raise TypeError(
962+
"config_file_parser_class must be a subclass of "
963+
"ConfigFileParser (such as DefaultConfigFileParser, "
964+
"YAMLConfigFileParser, etc.). "
965+
"Got: %r. Perhaps you meant to use formatter_class?"
966+
% (config_file_parser_class,)
967+
)
927968

928969
self._default_config_files = default_config_files
929970
self._ignore_unknown_config_file_keys = ignore_unknown_config_file_keys

0 commit comments

Comments
 (0)