###
6.20.5.4 拡張の例

以下に `optparse` モジュールを拡張する例をいくつか示します。

まず、オプション解析で大小文字の区別をしないように変更しましょう:

    from optparse import Option, OptionParser, _match_abbrev

    # This case-insensitive option parser relies on having a
    # case-insensitive dictionary type available.  Here's one
    # for Python 2.2.  Note that a *real* case-insensitive
    # dictionary type would also have to implement __new__(),
    # update(), and setdefault() -- but that's not the point
    # of this exercise.

    class caseless_dict (dict):
        def __setitem__ (self, key, value):
            dict.__setitem__(self, key.lower(), value)

        def __getitem__ (self, key):
            return dict.__getitem__(self, key.lower())

        def get (self, key, default=None):
            return dict.get(self, key.lower())

        def has_key (self, key):
            return dict.has_key(self, key.lower())

    class CaselessOptionParser (OptionParser):

        def _create_option_list (self):
            self.option_list = []
            self._short_opt = caseless_dict()
            self._long_opt = caseless_dict()
            self._long_opts = []
            self.defaults = {}

        def _match_long_opt (self, opt):
            return _match_abbrev(opt.lower(), self._long_opt.keys())

    if __name__ == "__main__":
        from optik.errors import OptionConflictError

        # test 1: no options to start with
        parser = CaselessOptionParser()
        try:
            parser.add_option("-H", dest="blah")
        except OptionConflictError:
            print "ok: got OptionConflictError for -H"
        else:
            print "not ok: no conflict between -h and -H"

        parser.add_option("-f", "--file", dest="file")
        #print `parser.get_option("-f")`
        #print `parser.get_option("-F")`
        #print `parser.get_option("--file")`
        #print `parser.get_option("--fIlE")`
        (options, args) = parser.parse_args(["--FiLe", "foo"])
        assert options.file == "foo", options.file
        print "ok: case insensitive long options work"

        (options, args) = parser.parse_args(["-F", "bar"])
        assert options.file == "bar", options.file
        print "ok: case insensitive short options work"

次に、 `optparse` で ``必須オプション'' を実装する方法を二つ 挙げます。

その 1: アプリケーションが引数を解析した後に必ず呼び出すメソッドを `OptionParser` に追加します:

    import optparse

    class OptionParser (optparse.OptionParser):

        def check_required (self, opt):
          option = self.get_option(opt)

          # Assumes the option's 'default' is set to None!
          if getattr(self.values, option.dest) is None:
              self.error("%s option not supplied" % option)

    parser = OptionParser()
    parser.add_option("-v", action="count", dest="verbose")
    parser.add_option("-f", "--file", default=None)
    (options, args) = parser.parse_args()

    print "verbose:", options.verbose
    print "file:", options.file
    parser.check_required("-f")

その 2: `Option` を拡張して `required` 属性を追加します; `OptionParser` を拡張して、必須オプションが引数解析語に存在する ことを確認させます:

    import optparse

    class Option (optparse.Option):
        ATTRS = optparse.Option.ATTRS + ['required']

        def _check_required (self):
            if self.required and not self.takes_value():
                raise OptionError(
                    "required flag set for option that doesn't take a value",
                     self)

        # Make sure _check_required() is called from the constructor!
        CHECK_METHODS = optparse.Option.CHECK_METHODS + [_check_required]

        def process (self, opt, value, values, parser):
            optparse.Option.process(self, opt, value, values, parser)
            parser.option_seen[self] = 1

    class OptionParser (optparse.OptionParser):

        def _init_parsing_state (self):
            optparse.OptionParser._init_parsing_state(self)
            self.option_seen = {}

        def check_values (self, values, args):
            for option in self.option_list:
                if (isinstance(option, Option) and
                    option.required and
                    not self.option_seen.has_key(option)):
                    self.error("%s not supplied" % option)
            return (values, args)

    parser = OptionParser(option_list=[
        Option("-v", action="count", dest="verbose"),
        Option("-f", "--file", required=1)])
    (options, args) = parser.parse_args()

    print "verbose:", options.verbose
    print "file:", options.file