Commits

Anonymous committed e228920 Draft

Supporting store_const (issue #1)

  • Participants
  • Parent commits e49e340

Comments (0)

Files changed (1)

File argparse_config.src/argparse_config/__init__.py

 """
 Author: tikitu
 """
-from argparse import _SubParsersAction, _StoreAction
+from argparse import _SubParsersAction, _StoreAction, _StoreConstAction
 
 __version__ = '0.4a1'
 
         self.value = value
         self.type_transformer = type_transformer
 
-def process_parser_action(action, config_parser, section_name='default'):
+def process_parser_action(action, config_parser, section_name='default', is_store_const=False):
     for option_string in action.option_strings:
         option_string = convert_option_string(option_string)
         if config_parser.has_option(section_name, option_string):
-            value = config_parser.get(section_name, option_string)
-            type_transformer = action.type if action.type is not None else lambda x:x
-            try:
-                action.default = type_transformer(value)
-            except:
-                raise DefaultError(section_name, option_string, value, type_transformer)
+            if is_store_const:
+                action.default = action.const
+            else:
+                value = config_parser.get(section_name, option_string)
+                type_transformer = action.type if action.type is not None else lambda x:x
+                try:
+                    action.default = type_transformer(value)
+                except:
+                    raise DefaultError(section_name, option_string, value, type_transformer)
             action.required = False
 
 def set_defaults(argparser, config_parser):
         for action in argparser._actions:
             if isinstance(action, _StoreAction):
                 process_parser_action(action, config_parser)
-            if isinstance(action, _SubParsersAction):
+            elif isinstance(action, _StoreConstAction):
+                process_parser_action(action, config_parser, is_store_const=True)
+            elif isinstance(action, _SubParsersAction):
                 for command, sub_parser in action.choices.items():
                     if config_parser.has_section(command):
                         for sub_action in sub_parser._actions: