Added a test for the ability to specify a class attribute in Formatter configuration...
[python.git] / Doc / lib / required_2.py
blob421514af057499b81ddb413fc246d4a4b5aeff3b
1 import optparse
3 class Option (optparse.Option):
4 ATTRS = optparse.Option.ATTRS + ['required']
6 def _check_required (self):
7 if self.required and not self.takes_value():
8 raise OptionError(
9 "required flag set for option that doesn't take a value",
10 self)
12 # Make sure _check_required() is called from the constructor!
13 CHECK_METHODS = optparse.Option.CHECK_METHODS + [_check_required]
15 def process (self, opt, value, values, parser):
16 optparse.Option.process(self, opt, value, values, parser)
17 parser.option_seen[self] = 1
20 class OptionParser (optparse.OptionParser):
22 def _init_parsing_state (self):
23 optparse.OptionParser._init_parsing_state(self)
24 self.option_seen = {}
26 def check_values (self, values, args):
27 for option in self.option_list:
28 if (isinstance(option, Option) and
29 option.required and
30 not self.option_seen.has_key(option)):
31 self.error("%s not supplied" % option)
32 return (values, args)
35 parser = OptionParser(option_list=[
36 Option("-v", action="count", dest="verbose"),
37 Option("-f", "--file", required=1)])
38 (options, args) = parser.parse_args()
40 print "verbose:", options.verbose
41 print "file:", options.file