comparison configuration/configuration.py @ 88:36cf1d9bf40b

slightly improve type system
author Jeff Hammel <jhammel@mozilla.com>
date Fri, 27 Apr 2012 15:18:24 -0700
parents 928654373755
children 0804a706d6bf
comparison
equal deleted inserted replaced
87:928654373755 88:36cf1d9bf40b
219 types = {bool: BoolCLI(), 219 types = {bool: BoolCLI(),
220 int: IntCLI(), 220 int: IntCLI(),
221 float: FloatCLI(), 221 float: FloatCLI(),
222 list: ListCLI(), 222 list: ListCLI(),
223 dict: DictCLI(), 223 dict: DictCLI(),
224 str: BaseCLI(),
224 None: BaseCLI()} # default 225 None: BaseCLI()} # default
225 226
226 __all__ += [i.__class__.__name__ for i in types.values()] 227 __all__ += [i.__class__.__name__ for i in types.values()]
227 228
228 class Configuration(optparse.OptionParser): 229 class Configuration(optparse.OptionParser):
354 355
355 def cli_formatter(self, option): 356 def cli_formatter(self, option):
356 handler = self.types[self.option_dict[option].get('type')] 357 handler = self.types[self.option_dict[option].get('type')]
357 return getattr(handler, 'take_action', lambda x: 1) 358 return getattr(handler, 'take_action', lambda x: 1)
358 359
360 def option_type(self, name):
361 value = self.option_dict[name]
362 if 'type' in value:
363 return value['type']
364 if 'default' in value:
365 return type(value['default'])
366
359 def optparse_options(self, parser): 367 def optparse_options(self, parser):
360 """add optparse options to a OptionParser instance""" 368 """add optparse options to a OptionParser instance"""
361 for key, value in self.items(): 369 for key, value in self.items():
362 handler = self.types[value.get('type')] 370 handler = self.types[self.option_type(key)]
363 args, kw = handler(key, value) 371 args, kw = handler(key, value)
364 if not args: 372 if not args:
365 # No CLI interface 373 # No CLI interface
366 continue 374 continue
367 parser.add_option(*args, **kw) 375 parser.add_option(*args, **kw)