From: A. Jesse Jiryu Davis Date: Thu, 16 May 2013 18:14:27 +0000 (-0400) Subject: Make options instance more dict-like. X-Git-Tag: v3.1.0~55^2~3 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=5868b7edacb631ee323c2eb868cc2c1154050d57;p=thirdparty%2Ftornado.git Make options instance more dict-like. --- diff --git a/tornado/options.py b/tornado/options.py index faf0e164c..04ae44376 100644 --- a/tornado/options.py +++ b/tornado/options.py @@ -101,6 +101,27 @@ class OptionParser(object): return self._options[name].set(value) raise AttributeError("Unrecognized option %r" % name) + def __iter__(self): + return iter(self._options) + + def __getitem__(self, item): + return self._options[item] + + def items(self): + """A sequence of (name, value) pairs.""" + return [(name, opt.value()) for name, opt in self._options.items()] + + def as_dict(self): + """A dict of names and values. + + Useful for copying options into Application settings:: + + from tornado import options + options.parse_command_line() + application = Application(handler, **options.options.as_dict()) + """ + return dict(self.items()) + def define(self, name, default=None, type=None, help=None, metavar=None, multiple=False, group=None, callback=None): """Defines a new command line option. diff --git a/tornado/test/options_test.py b/tornado/test/options_test.py index dc52a82a4..2c1f4035e 100644 --- a/tornado/test/options_test.py +++ b/tornado/test/options_test.py @@ -113,6 +113,31 @@ class OptionsTest(unittest.TestCase): options.foo = 2 self.assertEqual(values, [2]) + def _sample_options(self): + options = OptionParser() + options.define('a', default=1) + options.define('b', default=2) + return options + + def test_iter(self): + options = self._sample_options() + # OptionParsers always define 'help'. + self.assertEqual(set(['a', 'b', 'help']), set(iter(options))) + + def test_items(self): + options = self._sample_options() + # OptionParsers always define 'help'. + expected = [('a', 1), ('b', 2), ('help', options.help)] + actual = sorted(options.items()) + self.assertEqual(expected, actual) + + def test_as_dict(self): + options = self._sample_options() + options_dict = options.as_dict() + # OptionParsers always define 'help'. + expected = {'a': 1, 'b': 2, 'help': options.help} + self.assertEqual(expected, options_dict) + @unittest.skipIf(mock is None, 'mock package not present') def test_mock_patch(self): # ensure that our setattr hooks don't interfere with mock.patch