instance_id
string
pull_number
int64
repo
string
version
string
base_commit
string
created_at
string
patch
string
test_patch
string
non_py_patch
string
new_components
list
FAIL_TO_PASS
list
PASS_TO_PASS
list
pull_request_text
string
issue_text
string
readmes
list
files
list
environment_setup_commit
string
patch-detailed
string
natural-detailed
string
patch-brief
string
natural-brief
string
tornadoweb__tornado-789
789
tornadoweb/tornado
null
833d6975c320836ddc3a20fde681fdccbdcb82ed
2013-05-16T18:15:55Z
diff --git a/tornado/options.py b/tornado/options.py index faf0e164cc..04692f7a83 100644 --- a/tornado/options.py +++ b/tornado/options.py @@ -101,6 +101,44 @@ def __setattr__(self, name, value): 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].value() + + def items(self): + """A sequence of (name, value) pairs.""" + return [(name, opt.value()) for name, opt in self._options.items()] + + def groups(self): + """The set of option-groups created by ``define``.""" + return set(opt.group_name for opt in self._options.values()) + + def group_dict(self, group): + """The names and values of options in a group. + + Useful for copying options into Application settings:: + + from tornado.options import define, parse_command_line, options + + define('template_path', group='application') + define('static_path', group='application') + + parse_command_line() + + application = Application( + handlers, **options.group_dict('application')) + """ + return dict( + (name, opt.value()) for name, opt in self._options.items() + if not group or group == opt.group_name) + + def as_dict(self): + """The names and values of all options.""" + return dict( + (name, opt.value()) for name, opt in self._options.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 dc52a82a49..23ce0fe458 100644 --- a/tornado/test/options_test.py +++ b/tornado/test/options_test.py @@ -113,6 +113,47 @@ def test_setattr_with_callback(self): 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_getitem(self): + options = self._sample_options() + self.assertEqual(1, options['a']) + + 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() + expected = {'a': 1, 'b': 2, 'help': options.help} + self.assertEqual(expected, options.as_dict()) + + def test_group_dict(self): + options = OptionParser() + options.define('a', default=1) + options.define('b', group='b_group', default=2) + + frame = sys._getframe(0) + this_file = frame.f_code.co_filename + self.assertEqual(set(['b_group', '', this_file]), options.groups()) + + b_group_dict = options.group_dict('b_group') + self.assertEqual({'b': 2}, b_group_dict) + + self.assertEqual({}, options.group_dict('nonexistent')) + @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
[ { "components": [ { "doc": "", "lines": [ 104, 105 ], "name": "OptionParser.__iter__", "signature": "def __iter__(self):", "type": "function" }, { "doc": "", "lines": [ 107, 108 ], ...
[ "tornado/test/options_test.py::OptionsTest::test_as_dict", "tornado/test/options_test.py::OptionsTest::test_getitem", "tornado/test/options_test.py::OptionsTest::test_group_dict", "tornado/test/options_test.py::OptionsTest::test_items", "tornado/test/options_test.py::OptionsTest::test_iter" ]
[ "tornado/test/options_test.py::OptionsTest::test_help", "tornado/test/options_test.py::OptionsTest::test_mock_patch", "tornado/test/options_test.py::OptionsTest::test_multiple_int", "tornado/test/options_test.py::OptionsTest::test_multiple_string", "tornado/test/options_test.py::OptionsTest::test_parse_call...
<request> Make options instance more dict-like. In my Motor-Blog application, I find myself copying a lot of options from tornado.options into Application(). I thought this would be nice: application = Application(handler, **options.options.as_dict()) ... so I added as_dict() and some dict-like features to OptionParser. ---------- </request>
[]
[ { "content": "#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unle...
b5dad636aaba94f86a3c00ca6ec49c79ff4313b2
You will be provided with a partial code base and an feature request which requires a new feature to add in the code repository. <request> Make options instance more dict-like. In my Motor-Blog application, I find myself copying a lot of options from tornado.options into Application(). I thought this would be nice: application = Application(handler, **options.options.as_dict()) ... so I added as_dict() and some dict-like features to OptionParser. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in tornado/options.py] (definition of OptionParser.__iter__:) def __iter__(self): (definition of OptionParser.__getitem__:) def __getitem__(self, item): (definition of OptionParser.items:) def items(self): """A sequence of (name, value) pairs.""" (definition of OptionParser.groups:) def groups(self): """The set of option-groups created by ``define``.""" (definition of OptionParser.group_dict:) def group_dict(self, group): """The names and values of options in a group. Useful for copying options into Application settings:: from tornado.options import define, parse_command_line, options define('template_path', group='application') define('static_path', group='application') parse_command_line() application = Application( handlers, **options.group_dict('application'))""" (definition of OptionParser.as_dict:) def as_dict(self): """The names and values of all options.""" [end of new definitions in tornado/options.py] </definitions> All the involved readme files and code files are listed below with their contents. If a file's content is indicated as empty, it means that the file does not yet exist in the current repository and needs to be created with new content. <code> [start of tornado/options.py] 1 #!/usr/bin/env python 2 # 3 # Copyright 2009 Facebook 4 # 5 # Licensed under the Apache License, Version 2.0 (the "License"); you may 6 # not use this file except in compliance with the License. You may obtain 7 # a copy of the License at 8 # 9 # http://www.apache.org/licenses/LICENSE-2.0 10 # 11 # Unless required by applicable law or agreed to in writing, software 12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 # License for the specific language governing permissions and limitations 15 # under the License. 16 17 """A command line parsing module that lets modules define their own options. 18 19 Each module defines its own options which are added to the global 20 option namespace, e.g.:: 21 22 from tornado.options import define, options 23 24 define("mysql_host", default="127.0.0.1:3306", help="Main user DB") 25 define("memcache_hosts", default="127.0.0.1:11011", multiple=True, 26 help="Main user memcache servers") 27 28 def connect(): 29 db = database.Connection(options.mysql_host) 30 ... 31 32 The ``main()`` method of your application does not need to be aware of all of 33 the options used throughout your program; they are all automatically loaded 34 when the modules are loaded. However, all modules that define options 35 must have been imported before the command line is parsed. 36 37 Your ``main()`` method can parse the command line or parse a config file with 38 either:: 39 40 tornado.options.parse_command_line() 41 # or 42 tornado.options.parse_config_file("/etc/server.conf") 43 44 Command line formats are what you would expect (``--myoption=myvalue``). 45 Config files are just Python files. Global names become options, e.g.:: 46 47 myoption = "myvalue" 48 myotheroption = "myothervalue" 49 50 We support `datetimes <datetime.datetime>`, `timedeltas 51 <datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to 52 `define`). We also accept multi-value options. See the documentation for 53 `define()` below. 54 55 `tornado.options.options` is a singleton instance of `OptionParser`, and 56 the top-level functions in this module (`define`, `parse_command_line`, etc) 57 simply call methods on it. You may create additional `OptionParser` 58 instances to define isolated sets of options, such as for subcommands. 59 """ 60 61 from __future__ import absolute_import, division, print_function, with_statement 62 63 import datetime 64 import numbers 65 import re 66 import sys 67 import os 68 import textwrap 69 70 from tornado.escape import _unicode 71 from tornado.log import define_logging_options 72 from tornado import stack_context 73 from tornado.util import basestring_type, exec_in 74 75 76 class Error(Exception): 77 """Exception raised by errors in the options module.""" 78 pass 79 80 81 class OptionParser(object): 82 """A collection of options, a dictionary with object-like access. 83 84 Normally accessed via static functions in the `tornado.options` module, 85 which reference a global instance. 86 """ 87 def __init__(self): 88 # we have to use self.__dict__ because we override setattr. 89 self.__dict__['_options'] = {} 90 self.__dict__['_parse_callbacks'] = [] 91 self.define("help", type=bool, help="show this help information", 92 callback=self._help_callback) 93 94 def __getattr__(self, name): 95 if isinstance(self._options.get(name), _Option): 96 return self._options[name].value() 97 raise AttributeError("Unrecognized option %r" % name) 98 99 def __setattr__(self, name, value): 100 if isinstance(self._options.get(name), _Option): 101 return self._options[name].set(value) 102 raise AttributeError("Unrecognized option %r" % name) 103 104 def define(self, name, default=None, type=None, help=None, metavar=None, 105 multiple=False, group=None, callback=None): 106 """Defines a new command line option. 107 108 If ``type`` is given (one of str, float, int, datetime, or timedelta) 109 or can be inferred from the ``default``, we parse the command line 110 arguments based on the given type. If ``multiple`` is True, we accept 111 comma-separated values, and the option value is always a list. 112 113 For multi-value integers, we also accept the syntax ``x:y``, which 114 turns into ``range(x, y)`` - very useful for long integer ranges. 115 116 ``help`` and ``metavar`` are used to construct the 117 automatically generated command line help string. The help 118 message is formatted like:: 119 120 --name=METAVAR help string 121 122 ``group`` is used to group the defined options in logical 123 groups. By default, command line options are grouped by the 124 file in which they are defined. 125 126 Command line option names must be unique globally. They can be parsed 127 from the command line with `parse_command_line` or parsed from a 128 config file with `parse_config_file`. 129 130 If a ``callback`` is given, it will be run with the new value whenever 131 the option is changed. This can be used to combine command-line 132 and file-based options:: 133 134 define("config", type=str, help="path to config file", 135 callback=lambda path: parse_config_file(path, final=False)) 136 137 With this definition, options in the file specified by ``--config`` will 138 override options set earlier on the command line, but can be overridden 139 by later flags. 140 """ 141 if name in self._options: 142 raise Error("Option %r already defined in %s", name, 143 self._options[name].file_name) 144 frame = sys._getframe(0) 145 options_file = frame.f_code.co_filename 146 file_name = frame.f_back.f_code.co_filename 147 if file_name == options_file: 148 file_name = "" 149 if type is None: 150 if not multiple and default is not None: 151 type = default.__class__ 152 else: 153 type = str 154 if group: 155 group_name = group 156 else: 157 group_name = file_name 158 self._options[name] = _Option(name, file_name=file_name, 159 default=default, type=type, help=help, 160 metavar=metavar, multiple=multiple, 161 group_name=group_name, 162 callback=callback) 163 164 def parse_command_line(self, args=None, final=True): 165 """Parses all options given on the command line (defaults to 166 `sys.argv`). 167 168 Note that ``args[0]`` is ignored since it is the program name 169 in `sys.argv`. 170 171 We return a list of all arguments that are not parsed as options. 172 173 If ``final`` is ``False``, parse callbacks will not be run. 174 This is useful for applications that wish to combine configurations 175 from multiple sources. 176 """ 177 if args is None: 178 args = sys.argv 179 remaining = [] 180 for i in range(1, len(args)): 181 # All things after the last option are command line arguments 182 if not args[i].startswith("-"): 183 remaining = args[i:] 184 break 185 if args[i] == "--": 186 remaining = args[i + 1:] 187 break 188 arg = args[i].lstrip("-") 189 name, equals, value = arg.partition("=") 190 name = name.replace('-', '_') 191 if not name in self._options: 192 self.print_help() 193 raise Error('Unrecognized command line option: %r' % name) 194 option = self._options[name] 195 if not equals: 196 if option.type == bool: 197 value = "true" 198 else: 199 raise Error('Option %r requires a value' % name) 200 option.parse(value) 201 202 if final: 203 self.run_parse_callbacks() 204 205 return remaining 206 207 def parse_config_file(self, path, final=True): 208 """Parses and loads the Python config file at the given path. 209 210 If ``final`` is ``False``, parse callbacks will not be run. 211 This is useful for applications that wish to combine configurations 212 from multiple sources. 213 """ 214 config = {} 215 with open(path) as f: 216 exec_in(f.read(), config, config) 217 for name in config: 218 if name in self._options: 219 self._options[name].set(config[name]) 220 221 if final: 222 self.run_parse_callbacks() 223 224 def print_help(self, file=None): 225 """Prints all the command line options to stderr (or another file).""" 226 if file is None: 227 file = sys.stderr 228 print("Usage: %s [OPTIONS]" % sys.argv[0], file=file) 229 print("\nOptions:\n", file=file) 230 by_group = {} 231 for option in self._options.values(): 232 by_group.setdefault(option.group_name, []).append(option) 233 234 for filename, o in sorted(by_group.items()): 235 if filename: 236 print("\n%s options:\n" % os.path.normpath(filename), file=file) 237 o.sort(key=lambda option: option.name) 238 for option in o: 239 prefix = option.name 240 if option.metavar: 241 prefix += "=" + option.metavar 242 description = option.help or "" 243 if option.default is not None and option.default != '': 244 description += " (default %s)" % option.default 245 lines = textwrap.wrap(description, 79 - 35) 246 if len(prefix) > 30 or len(lines) == 0: 247 lines.insert(0, '') 248 print(" --%-30s %s" % (prefix, lines[0]), file=file) 249 for line in lines[1:]: 250 print("%-34s %s" % (' ', line), file=file) 251 print(file=file) 252 253 def _help_callback(self, value): 254 if value: 255 self.print_help() 256 sys.exit(0) 257 258 def add_parse_callback(self, callback): 259 """Adds a parse callback, to be invoked when option parsing is done.""" 260 self._parse_callbacks.append(stack_context.wrap(callback)) 261 262 def run_parse_callbacks(self): 263 for callback in self._parse_callbacks: 264 callback() 265 266 def mockable(self): 267 """Returns a wrapper around self that is compatible with 268 `mock.patch <unittest.mock.patch>`. 269 270 The `mock.patch <unittest.mock.patch>` function (included in 271 the standard library `unittest.mock` package since Python 3.3, 272 or in the third-party ``mock`` package for older versions of 273 Python) is incompatible with objects like ``options`` that 274 override ``__getattr__`` and ``__setattr__``. This function 275 returns an object that can be used with `mock.patch.object 276 <unittest.mock.patch.object>` to modify option values:: 277 278 with mock.patch.object(options.mockable(), 'name', value): 279 assert options.name == value 280 """ 281 return _Mockable(self) 282 283 284 class _Mockable(object): 285 """`mock.patch` compatible wrapper for `OptionParser`. 286 287 As of ``mock`` version 1.0.1, when an object uses ``__getattr__`` 288 hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete 289 the attribute it set instead of setting a new one (assuming that 290 the object does not catpure ``__setattr__``, so the patch 291 created a new attribute in ``__dict__``). 292 293 _Mockable's getattr and setattr pass through to the underlying 294 OptionParser, and delattr undoes the effect of a previous setattr. 295 """ 296 def __init__(self, options): 297 # Modify __dict__ directly to bypass __setattr__ 298 self.__dict__['_options'] = options 299 self.__dict__['_originals'] = {} 300 301 def __getattr__(self, name): 302 return getattr(self._options, name) 303 304 def __setattr__(self, name, value): 305 assert name not in self._originals, "don't reuse mockable objects" 306 self._originals[name] = getattr(self._options, name) 307 setattr(self._options, name, value) 308 309 def __delattr__(self, name): 310 setattr(self._options, name, self._originals.pop(name)) 311 312 313 class _Option(object): 314 def __init__(self, name, default=None, type=basestring_type, help=None, 315 metavar=None, multiple=False, file_name=None, group_name=None, 316 callback=None): 317 if default is None and multiple: 318 default = [] 319 self.name = name 320 self.type = type 321 self.help = help 322 self.metavar = metavar 323 self.multiple = multiple 324 self.file_name = file_name 325 self.group_name = group_name 326 self.callback = callback 327 self.default = default 328 self._value = None 329 330 def value(self): 331 return self.default if self._value is None else self._value 332 333 def parse(self, value): 334 _parse = { 335 datetime.datetime: self._parse_datetime, 336 datetime.timedelta: self._parse_timedelta, 337 bool: self._parse_bool, 338 basestring_type: self._parse_string, 339 }.get(self.type, self.type) 340 if self.multiple: 341 self._value = [] 342 for part in value.split(","): 343 if issubclass(self.type, numbers.Integral): 344 # allow ranges of the form X:Y (inclusive at both ends) 345 lo, _, hi = part.partition(":") 346 lo = _parse(lo) 347 hi = _parse(hi) if hi else lo 348 self._value.extend(range(lo, hi + 1)) 349 else: 350 self._value.append(_parse(part)) 351 else: 352 self._value = _parse(value) 353 if self.callback is not None: 354 self.callback(self._value) 355 return self.value() 356 357 def set(self, value): 358 if self.multiple: 359 if not isinstance(value, list): 360 raise Error("Option %r is required to be a list of %s" % 361 (self.name, self.type.__name__)) 362 for item in value: 363 if item != None and not isinstance(item, self.type): 364 raise Error("Option %r is required to be a list of %s" % 365 (self.name, self.type.__name__)) 366 else: 367 if value != None and not isinstance(value, self.type): 368 raise Error("Option %r is required to be a %s (%s given)" % 369 (self.name, self.type.__name__, type(value))) 370 self._value = value 371 if self.callback is not None: 372 self.callback(self._value) 373 374 # Supported date/time formats in our options 375 _DATETIME_FORMATS = [ 376 "%a %b %d %H:%M:%S %Y", 377 "%Y-%m-%d %H:%M:%S", 378 "%Y-%m-%d %H:%M", 379 "%Y-%m-%dT%H:%M", 380 "%Y%m%d %H:%M:%S", 381 "%Y%m%d %H:%M", 382 "%Y-%m-%d", 383 "%Y%m%d", 384 "%H:%M:%S", 385 "%H:%M", 386 ] 387 388 def _parse_datetime(self, value): 389 for format in self._DATETIME_FORMATS: 390 try: 391 return datetime.datetime.strptime(value, format) 392 except ValueError: 393 pass 394 raise Error('Unrecognized date/time format: %r' % value) 395 396 _TIMEDELTA_ABBREVS = [ 397 ('hours', ['h']), 398 ('minutes', ['m', 'min']), 399 ('seconds', ['s', 'sec']), 400 ('milliseconds', ['ms']), 401 ('microseconds', ['us']), 402 ('days', ['d']), 403 ('weeks', ['w']), 404 ] 405 406 _TIMEDELTA_ABBREV_DICT = dict( 407 (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS 408 for abbrev in abbrevs) 409 410 _FLOAT_PATTERN = r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?' 411 412 _TIMEDELTA_PATTERN = re.compile( 413 r'\s*(%s)\s*(\w*)\s*' % _FLOAT_PATTERN, re.IGNORECASE) 414 415 def _parse_timedelta(self, value): 416 try: 417 sum = datetime.timedelta() 418 start = 0 419 while start < len(value): 420 m = self._TIMEDELTA_PATTERN.match(value, start) 421 if not m: 422 raise Exception() 423 num = float(m.group(1)) 424 units = m.group(2) or 'seconds' 425 units = self._TIMEDELTA_ABBREV_DICT.get(units, units) 426 sum += datetime.timedelta(**{units: num}) 427 start = m.end() 428 return sum 429 except Exception: 430 raise 431 432 def _parse_bool(self, value): 433 return value.lower() not in ("false", "0", "f") 434 435 def _parse_string(self, value): 436 return _unicode(value) 437 438 439 options = OptionParser() 440 """Global options object. 441 442 All defined options are available as attributes on this object. 443 """ 444 445 446 def define(name, default=None, type=None, help=None, metavar=None, 447 multiple=False, group=None, callback=None): 448 """Defines an option in the global namespace. 449 450 See `OptionParser.define`. 451 """ 452 return options.define(name, default=default, type=type, help=help, 453 metavar=metavar, multiple=multiple, group=group, 454 callback=callback) 455 456 457 def parse_command_line(args=None, final=True): 458 """Parses global options from the command line. 459 460 See `OptionParser.parse_command_line`. 461 """ 462 return options.parse_command_line(args, final=final) 463 464 465 def parse_config_file(path, final=True): 466 """Parses global options from a config file. 467 468 See `OptionParser.parse_config_file`. 469 """ 470 return options.parse_config_file(path, final=final) 471 472 473 def print_help(file=None): 474 """Prints all the command line options to stderr (or another file). 475 476 See `OptionParser.print_help`. 477 """ 478 return options.print_help(file) 479 480 481 def add_parse_callback(callback): 482 """Adds a parse callback, to be invoked when option parsing is done. 483 484 See `OptionParser.add_parse_callback` 485 """ 486 options.add_parse_callback(callback) 487 488 489 # Default options 490 define_logging_options(options) 491 [end of tornado/options.py] </code> Please solve the feature request with adding the functions or classes between the <definitions> and </definitions>. You do not need to output any changes or edits for description files like .md or .rst files. I need you to make multiple edits across one or more files in a repository to implement a specific feature or improvement mentioned above. The edits should be output in patch format. Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files. <patch> diff --git a/src/code.py b/src/code.py --- a/src/code.py +++ b/src/code.py @@ -1,11 +1,14 @@ def factorial(a): + assert type(a) == int and a >= 0 res = 1 - while a >= 0: + while a >= 2: res *= a + a -= 1 return res # # # # def exact_dividion(x, y): + assert type(x) == type(y) == int and x > 0 and y > 0 return x % y == 0 diff --git a/src/demo.py b/src/demo.py new file mode 100644 --- /dev/null +++ b/src/demo.py @@ -0,0 +1,2 @@ +from code import factorial +print(factorial(5)) </patch> I need you to solve the provided feature request by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above. Respond below:
You will be provided with a partial code base and an feature request which requires a new feature to add in the code repository. <request> Make options instance more dict-like. In my Motor-Blog application, I find myself copying a lot of options from tornado.options into Application(). I thought this would be nice: application = Application(handler, **options.options.as_dict()) ... so I added as_dict() and some dict-like features to OptionParser. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in tornado/options.py] (definition of OptionParser.__iter__:) def __iter__(self): (definition of OptionParser.__getitem__:) def __getitem__(self, item): (definition of OptionParser.items:) def items(self): """A sequence of (name, value) pairs.""" (definition of OptionParser.groups:) def groups(self): """The set of option-groups created by ``define``.""" (definition of OptionParser.group_dict:) def group_dict(self, group): """The names and values of options in a group. Useful for copying options into Application settings:: from tornado.options import define, parse_command_line, options define('template_path', group='application') define('static_path', group='application') parse_command_line() application = Application( handlers, **options.group_dict('application'))""" (definition of OptionParser.as_dict:) def as_dict(self): """The names and values of all options.""" [end of new definitions in tornado/options.py] </definitions> All the involved readme files and code files are listed below with their contents. If a file's content is indicated as empty, it means that the file does not yet exist in the current repository and needs to be created with new content. <code> [start of tornado/options.py] #!/usr/bin/env python # # Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """A command line parsing module that lets modules define their own options. Each module defines its own options which are added to the global option namespace, e.g.:: from tornado.options import define, options define("mysql_host", default="127.0.0.1:3306", help="Main user DB") define("memcache_hosts", default="127.0.0.1:11011", multiple=True, help="Main user memcache servers") def connect(): db = database.Connection(options.mysql_host) ... The ``main()`` method of your application does not need to be aware of all of the options used throughout your program; they are all automatically loaded when the modules are loaded. However, all modules that define options must have been imported before the command line is parsed. Your ``main()`` method can parse the command line or parse a config file with either:: tornado.options.parse_command_line() # or tornado.options.parse_config_file("/etc/server.conf") Command line formats are what you would expect (``--myoption=myvalue``). Config files are just Python files. Global names become options, e.g.:: myoption = "myvalue" myotheroption = "myothervalue" We support `datetimes <datetime.datetime>`, `timedeltas <datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to `define`). We also accept multi-value options. See the documentation for `define()` below. `tornado.options.options` is a singleton instance of `OptionParser`, and the top-level functions in this module (`define`, `parse_command_line`, etc) simply call methods on it. You may create additional `OptionParser` instances to define isolated sets of options, such as for subcommands. """ from __future__ import absolute_import, division, print_function, with_statement import datetime import numbers import re import sys import os import textwrap from tornado.escape import _unicode from tornado.log import define_logging_options from tornado import stack_context from tornado.util import basestring_type, exec_in class Error(Exception): """Exception raised by errors in the options module.""" pass class OptionParser(object): """A collection of options, a dictionary with object-like access. Normally accessed via static functions in the `tornado.options` module, which reference a global instance. """ def __init__(self): # we have to use self.__dict__ because we override setattr. self.__dict__['_options'] = {} self.__dict__['_parse_callbacks'] = [] self.define("help", type=bool, help="show this help information", callback=self._help_callback) def __getattr__(self, name): if isinstance(self._options.get(name), _Option): return self._options[name].value() raise AttributeError("Unrecognized option %r" % name) def __setattr__(self, name, value): if isinstance(self._options.get(name), _Option): return self._options[name].set(value) raise AttributeError("Unrecognized option %r" % name) def define(self, name, default=None, type=None, help=None, metavar=None, multiple=False, group=None, callback=None): """Defines a new command line option. If ``type`` is given (one of str, float, int, datetime, or timedelta) or can be inferred from the ``default``, we parse the command line arguments based on the given type. If ``multiple`` is True, we accept comma-separated values, and the option value is always a list. For multi-value integers, we also accept the syntax ``x:y``, which turns into ``range(x, y)`` - very useful for long integer ranges. ``help`` and ``metavar`` are used to construct the automatically generated command line help string. The help message is formatted like:: --name=METAVAR help string ``group`` is used to group the defined options in logical groups. By default, command line options are grouped by the file in which they are defined. Command line option names must be unique globally. They can be parsed from the command line with `parse_command_line` or parsed from a config file with `parse_config_file`. If a ``callback`` is given, it will be run with the new value whenever the option is changed. This can be used to combine command-line and file-based options:: define("config", type=str, help="path to config file", callback=lambda path: parse_config_file(path, final=False)) With this definition, options in the file specified by ``--config`` will override options set earlier on the command line, but can be overridden by later flags. """ if name in self._options: raise Error("Option %r already defined in %s", name, self._options[name].file_name) frame = sys._getframe(0) options_file = frame.f_code.co_filename file_name = frame.f_back.f_code.co_filename if file_name == options_file: file_name = "" if type is None: if not multiple and default is not None: type = default.__class__ else: type = str if group: group_name = group else: group_name = file_name self._options[name] = _Option(name, file_name=file_name, default=default, type=type, help=help, metavar=metavar, multiple=multiple, group_name=group_name, callback=callback) def parse_command_line(self, args=None, final=True): """Parses all options given on the command line (defaults to `sys.argv`). Note that ``args[0]`` is ignored since it is the program name in `sys.argv`. We return a list of all arguments that are not parsed as options. If ``final`` is ``False``, parse callbacks will not be run. This is useful for applications that wish to combine configurations from multiple sources. """ if args is None: args = sys.argv remaining = [] for i in range(1, len(args)): # All things after the last option are command line arguments if not args[i].startswith("-"): remaining = args[i:] break if args[i] == "--": remaining = args[i + 1:] break arg = args[i].lstrip("-") name, equals, value = arg.partition("=") name = name.replace('-', '_') if not name in self._options: self.print_help() raise Error('Unrecognized command line option: %r' % name) option = self._options[name] if not equals: if option.type == bool: value = "true" else: raise Error('Option %r requires a value' % name) option.parse(value) if final: self.run_parse_callbacks() return remaining def parse_config_file(self, path, final=True): """Parses and loads the Python config file at the given path. If ``final`` is ``False``, parse callbacks will not be run. This is useful for applications that wish to combine configurations from multiple sources. """ config = {} with open(path) as f: exec_in(f.read(), config, config) for name in config: if name in self._options: self._options[name].set(config[name]) if final: self.run_parse_callbacks() def print_help(self, file=None): """Prints all the command line options to stderr (or another file).""" if file is None: file = sys.stderr print("Usage: %s [OPTIONS]" % sys.argv[0], file=file) print("\nOptions:\n", file=file) by_group = {} for option in self._options.values(): by_group.setdefault(option.group_name, []).append(option) for filename, o in sorted(by_group.items()): if filename: print("\n%s options:\n" % os.path.normpath(filename), file=file) o.sort(key=lambda option: option.name) for option in o: prefix = option.name if option.metavar: prefix += "=" + option.metavar description = option.help or "" if option.default is not None and option.default != '': description += " (default %s)" % option.default lines = textwrap.wrap(description, 79 - 35) if len(prefix) > 30 or len(lines) == 0: lines.insert(0, '') print(" --%-30s %s" % (prefix, lines[0]), file=file) for line in lines[1:]: print("%-34s %s" % (' ', line), file=file) print(file=file) def _help_callback(self, value): if value: self.print_help() sys.exit(0) def add_parse_callback(self, callback): """Adds a parse callback, to be invoked when option parsing is done.""" self._parse_callbacks.append(stack_context.wrap(callback)) def run_parse_callbacks(self): for callback in self._parse_callbacks: callback() def mockable(self): """Returns a wrapper around self that is compatible with `mock.patch <unittest.mock.patch>`. The `mock.patch <unittest.mock.patch>` function (included in the standard library `unittest.mock` package since Python 3.3, or in the third-party ``mock`` package for older versions of Python) is incompatible with objects like ``options`` that override ``__getattr__`` and ``__setattr__``. This function returns an object that can be used with `mock.patch.object <unittest.mock.patch.object>` to modify option values:: with mock.patch.object(options.mockable(), 'name', value): assert options.name == value """ return _Mockable(self) class _Mockable(object): """`mock.patch` compatible wrapper for `OptionParser`. As of ``mock`` version 1.0.1, when an object uses ``__getattr__`` hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete the attribute it set instead of setting a new one (assuming that the object does not catpure ``__setattr__``, so the patch created a new attribute in ``__dict__``). _Mockable's getattr and setattr pass through to the underlying OptionParser, and delattr undoes the effect of a previous setattr. """ def __init__(self, options): # Modify __dict__ directly to bypass __setattr__ self.__dict__['_options'] = options self.__dict__['_originals'] = {} def __getattr__(self, name): return getattr(self._options, name) def __setattr__(self, name, value): assert name not in self._originals, "don't reuse mockable objects" self._originals[name] = getattr(self._options, name) setattr(self._options, name, value) def __delattr__(self, name): setattr(self._options, name, self._originals.pop(name)) class _Option(object): def __init__(self, name, default=None, type=basestring_type, help=None, metavar=None, multiple=False, file_name=None, group_name=None, callback=None): if default is None and multiple: default = [] self.name = name self.type = type self.help = help self.metavar = metavar self.multiple = multiple self.file_name = file_name self.group_name = group_name self.callback = callback self.default = default self._value = None def value(self): return self.default if self._value is None else self._value def parse(self, value): _parse = { datetime.datetime: self._parse_datetime, datetime.timedelta: self._parse_timedelta, bool: self._parse_bool, basestring_type: self._parse_string, }.get(self.type, self.type) if self.multiple: self._value = [] for part in value.split(","): if issubclass(self.type, numbers.Integral): # allow ranges of the form X:Y (inclusive at both ends) lo, _, hi = part.partition(":") lo = _parse(lo) hi = _parse(hi) if hi else lo self._value.extend(range(lo, hi + 1)) else: self._value.append(_parse(part)) else: self._value = _parse(value) if self.callback is not None: self.callback(self._value) return self.value() def set(self, value): if self.multiple: if not isinstance(value, list): raise Error("Option %r is required to be a list of %s" % (self.name, self.type.__name__)) for item in value: if item != None and not isinstance(item, self.type): raise Error("Option %r is required to be a list of %s" % (self.name, self.type.__name__)) else: if value != None and not isinstance(value, self.type): raise Error("Option %r is required to be a %s (%s given)" % (self.name, self.type.__name__, type(value))) self._value = value if self.callback is not None: self.callback(self._value) # Supported date/time formats in our options _DATETIME_FORMATS = [ "%a %b %d %H:%M:%S %Y", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y%m%d %H:%M:%S", "%Y%m%d %H:%M", "%Y-%m-%d", "%Y%m%d", "%H:%M:%S", "%H:%M", ] def _parse_datetime(self, value): for format in self._DATETIME_FORMATS: try: return datetime.datetime.strptime(value, format) except ValueError: pass raise Error('Unrecognized date/time format: %r' % value) _TIMEDELTA_ABBREVS = [ ('hours', ['h']), ('minutes', ['m', 'min']), ('seconds', ['s', 'sec']), ('milliseconds', ['ms']), ('microseconds', ['us']), ('days', ['d']), ('weeks', ['w']), ] _TIMEDELTA_ABBREV_DICT = dict( (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS for abbrev in abbrevs) _FLOAT_PATTERN = r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?' _TIMEDELTA_PATTERN = re.compile( r'\s*(%s)\s*(\w*)\s*' % _FLOAT_PATTERN, re.IGNORECASE) def _parse_timedelta(self, value): try: sum = datetime.timedelta() start = 0 while start < len(value): m = self._TIMEDELTA_PATTERN.match(value, start) if not m: raise Exception() num = float(m.group(1)) units = m.group(2) or 'seconds' units = self._TIMEDELTA_ABBREV_DICT.get(units, units) sum += datetime.timedelta(**{units: num}) start = m.end() return sum except Exception: raise def _parse_bool(self, value): return value.lower() not in ("false", "0", "f") def _parse_string(self, value): return _unicode(value) options = OptionParser() """Global options object. All defined options are available as attributes on this object. """ def define(name, default=None, type=None, help=None, metavar=None, multiple=False, group=None, callback=None): """Defines an option in the global namespace. See `OptionParser.define`. """ return options.define(name, default=default, type=type, help=help, metavar=metavar, multiple=multiple, group=group, callback=callback) def parse_command_line(args=None, final=True): """Parses global options from the command line. See `OptionParser.parse_command_line`. """ return options.parse_command_line(args, final=final) def parse_config_file(path, final=True): """Parses global options from a config file. See `OptionParser.parse_config_file`. """ return options.parse_config_file(path, final=final) def print_help(file=None): """Prints all the command line options to stderr (or another file). See `OptionParser.print_help`. """ return options.print_help(file) def add_parse_callback(callback): """Adds a parse callback, to be invoked when option parsing is done. See `OptionParser.add_parse_callback` """ options.add_parse_callback(callback) # Default options define_logging_options(options) [end of tornado/options.py] </code> Please solve the feature request with adding the functions or classes between the <definitions> and </definitions>. You do not need to output any changes or edits for description files like .md or .rst files. I need you to make multiple edits across one or more files in a repository to implement a specific feature or improvement mentioned above. For each edit, output the changes in the following format: ``` <edit> [start of the snippet before editing in <file_path>] <code_before_edit> [end of the snippet before editing in <file_path>] [start of the snippet after editing in <file_path>] <code_after_edit> [end of the snippet after editing in <file_path>] </edit> ``` Notes: - The <file_path> is the relative path of the file being edited. - The <code_before_edit> snippet should include several lines before and after the modified region, unless the file was originally empty. - If a file was originally empty, leave <code_before_edit> blank but ensure <code_after_edit> includes the new content. - Ensure the edits are sequential and address all necessary changes to achieve the requested feature. Here is an example of the output format: ``` <edit> [start of the snippet before editing in src/code.py] def factorial(a): res = 1 while a >= 0: res *= a return res [end of the snippet before editing in src/code.py] [start of the snippet after editing in src/code.py] def factorial(a): assert type(a) == int and a >= 0 res = 1 while a >= 2: res *= a a -= 1 return res [end of the snippet after editing in src/code.py] </edit> <edit> [start of the snippet before editing in src/code.py] def exact_dividion(x, y): return x % y == 0 [end of the snippet before editing in src/code.py] [start of the snippet after editing in src/code.py] def exact_dividion(x, y): assert type(x) == type(y) == int and x > 0 and y > 0 return x % y == 0 [end of the snippet after editing in src/code.py] </edit> <edit> [start of the snippet before editing in src/demo.py] [end of the snippet before editing in src/demo.py] [start of the snippet after editing in src/demo.py] from code import factorial print(factorial(5)) [end of the snippet after editing in src/demo.py] </edit> ``` I need you to solve the feature request with a series of edits in the format shown above. Respond below:
You will be provided with a partial code base and an feature request which requires a new feature to add in the code repository. <request> Make options instance more dict-like. In my Motor-Blog application, I find myself copying a lot of options from tornado.options into Application(). I thought this would be nice: application = Application(handler, **options.options.as_dict()) ... so I added as_dict() and some dict-like features to OptionParser. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in tornado/options.py] (definition of OptionParser.__iter__:) def __iter__(self): (definition of OptionParser.__getitem__:) def __getitem__(self, item): (definition of OptionParser.items:) def items(self): (definition of OptionParser.groups:) def groups(self): (definition of OptionParser.group_dict:) def group_dict(self, group): (definition of OptionParser.as_dict:) def as_dict(self): [end of new definitions in tornado/options.py] </definitions> All the involved readme files and code files are listed below with their contents. If a file's content is indicated as empty, it means that the file does not yet exist in the current repository and needs to be created with new content. <code> [start of tornado/options.py] 1 #!/usr/bin/env python 2 # 3 # Copyright 2009 Facebook 4 # 5 # Licensed under the Apache License, Version 2.0 (the "License"); you may 6 # not use this file except in compliance with the License. You may obtain 7 # a copy of the License at 8 # 9 # http://www.apache.org/licenses/LICENSE-2.0 10 # 11 # Unless required by applicable law or agreed to in writing, software 12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 # License for the specific language governing permissions and limitations 15 # under the License. 16 17 """A command line parsing module that lets modules define their own options. 18 19 Each module defines its own options which are added to the global 20 option namespace, e.g.:: 21 22 from tornado.options import define, options 23 24 define("mysql_host", default="127.0.0.1:3306", help="Main user DB") 25 define("memcache_hosts", default="127.0.0.1:11011", multiple=True, 26 help="Main user memcache servers") 27 28 def connect(): 29 db = database.Connection(options.mysql_host) 30 ... 31 32 The ``main()`` method of your application does not need to be aware of all of 33 the options used throughout your program; they are all automatically loaded 34 when the modules are loaded. However, all modules that define options 35 must have been imported before the command line is parsed. 36 37 Your ``main()`` method can parse the command line or parse a config file with 38 either:: 39 40 tornado.options.parse_command_line() 41 # or 42 tornado.options.parse_config_file("/etc/server.conf") 43 44 Command line formats are what you would expect (``--myoption=myvalue``). 45 Config files are just Python files. Global names become options, e.g.:: 46 47 myoption = "myvalue" 48 myotheroption = "myothervalue" 49 50 We support `datetimes <datetime.datetime>`, `timedeltas 51 <datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to 52 `define`). We also accept multi-value options. See the documentation for 53 `define()` below. 54 55 `tornado.options.options` is a singleton instance of `OptionParser`, and 56 the top-level functions in this module (`define`, `parse_command_line`, etc) 57 simply call methods on it. You may create additional `OptionParser` 58 instances to define isolated sets of options, such as for subcommands. 59 """ 60 61 from __future__ import absolute_import, division, print_function, with_statement 62 63 import datetime 64 import numbers 65 import re 66 import sys 67 import os 68 import textwrap 69 70 from tornado.escape import _unicode 71 from tornado.log import define_logging_options 72 from tornado import stack_context 73 from tornado.util import basestring_type, exec_in 74 75 76 class Error(Exception): 77 """Exception raised by errors in the options module.""" 78 pass 79 80 81 class OptionParser(object): 82 """A collection of options, a dictionary with object-like access. 83 84 Normally accessed via static functions in the `tornado.options` module, 85 which reference a global instance. 86 """ 87 def __init__(self): 88 # we have to use self.__dict__ because we override setattr. 89 self.__dict__['_options'] = {} 90 self.__dict__['_parse_callbacks'] = [] 91 self.define("help", type=bool, help="show this help information", 92 callback=self._help_callback) 93 94 def __getattr__(self, name): 95 if isinstance(self._options.get(name), _Option): 96 return self._options[name].value() 97 raise AttributeError("Unrecognized option %r" % name) 98 99 def __setattr__(self, name, value): 100 if isinstance(self._options.get(name), _Option): 101 return self._options[name].set(value) 102 raise AttributeError("Unrecognized option %r" % name) 103 104 def define(self, name, default=None, type=None, help=None, metavar=None, 105 multiple=False, group=None, callback=None): 106 """Defines a new command line option. 107 108 If ``type`` is given (one of str, float, int, datetime, or timedelta) 109 or can be inferred from the ``default``, we parse the command line 110 arguments based on the given type. If ``multiple`` is True, we accept 111 comma-separated values, and the option value is always a list. 112 113 For multi-value integers, we also accept the syntax ``x:y``, which 114 turns into ``range(x, y)`` - very useful for long integer ranges. 115 116 ``help`` and ``metavar`` are used to construct the 117 automatically generated command line help string. The help 118 message is formatted like:: 119 120 --name=METAVAR help string 121 122 ``group`` is used to group the defined options in logical 123 groups. By default, command line options are grouped by the 124 file in which they are defined. 125 126 Command line option names must be unique globally. They can be parsed 127 from the command line with `parse_command_line` or parsed from a 128 config file with `parse_config_file`. 129 130 If a ``callback`` is given, it will be run with the new value whenever 131 the option is changed. This can be used to combine command-line 132 and file-based options:: 133 134 define("config", type=str, help="path to config file", 135 callback=lambda path: parse_config_file(path, final=False)) 136 137 With this definition, options in the file specified by ``--config`` will 138 override options set earlier on the command line, but can be overridden 139 by later flags. 140 """ 141 if name in self._options: 142 raise Error("Option %r already defined in %s", name, 143 self._options[name].file_name) 144 frame = sys._getframe(0) 145 options_file = frame.f_code.co_filename 146 file_name = frame.f_back.f_code.co_filename 147 if file_name == options_file: 148 file_name = "" 149 if type is None: 150 if not multiple and default is not None: 151 type = default.__class__ 152 else: 153 type = str 154 if group: 155 group_name = group 156 else: 157 group_name = file_name 158 self._options[name] = _Option(name, file_name=file_name, 159 default=default, type=type, help=help, 160 metavar=metavar, multiple=multiple, 161 group_name=group_name, 162 callback=callback) 163 164 def parse_command_line(self, args=None, final=True): 165 """Parses all options given on the command line (defaults to 166 `sys.argv`). 167 168 Note that ``args[0]`` is ignored since it is the program name 169 in `sys.argv`. 170 171 We return a list of all arguments that are not parsed as options. 172 173 If ``final`` is ``False``, parse callbacks will not be run. 174 This is useful for applications that wish to combine configurations 175 from multiple sources. 176 """ 177 if args is None: 178 args = sys.argv 179 remaining = [] 180 for i in range(1, len(args)): 181 # All things after the last option are command line arguments 182 if not args[i].startswith("-"): 183 remaining = args[i:] 184 break 185 if args[i] == "--": 186 remaining = args[i + 1:] 187 break 188 arg = args[i].lstrip("-") 189 name, equals, value = arg.partition("=") 190 name = name.replace('-', '_') 191 if not name in self._options: 192 self.print_help() 193 raise Error('Unrecognized command line option: %r' % name) 194 option = self._options[name] 195 if not equals: 196 if option.type == bool: 197 value = "true" 198 else: 199 raise Error('Option %r requires a value' % name) 200 option.parse(value) 201 202 if final: 203 self.run_parse_callbacks() 204 205 return remaining 206 207 def parse_config_file(self, path, final=True): 208 """Parses and loads the Python config file at the given path. 209 210 If ``final`` is ``False``, parse callbacks will not be run. 211 This is useful for applications that wish to combine configurations 212 from multiple sources. 213 """ 214 config = {} 215 with open(path) as f: 216 exec_in(f.read(), config, config) 217 for name in config: 218 if name in self._options: 219 self._options[name].set(config[name]) 220 221 if final: 222 self.run_parse_callbacks() 223 224 def print_help(self, file=None): 225 """Prints all the command line options to stderr (or another file).""" 226 if file is None: 227 file = sys.stderr 228 print("Usage: %s [OPTIONS]" % sys.argv[0], file=file) 229 print("\nOptions:\n", file=file) 230 by_group = {} 231 for option in self._options.values(): 232 by_group.setdefault(option.group_name, []).append(option) 233 234 for filename, o in sorted(by_group.items()): 235 if filename: 236 print("\n%s options:\n" % os.path.normpath(filename), file=file) 237 o.sort(key=lambda option: option.name) 238 for option in o: 239 prefix = option.name 240 if option.metavar: 241 prefix += "=" + option.metavar 242 description = option.help or "" 243 if option.default is not None and option.default != '': 244 description += " (default %s)" % option.default 245 lines = textwrap.wrap(description, 79 - 35) 246 if len(prefix) > 30 or len(lines) == 0: 247 lines.insert(0, '') 248 print(" --%-30s %s" % (prefix, lines[0]), file=file) 249 for line in lines[1:]: 250 print("%-34s %s" % (' ', line), file=file) 251 print(file=file) 252 253 def _help_callback(self, value): 254 if value: 255 self.print_help() 256 sys.exit(0) 257 258 def add_parse_callback(self, callback): 259 """Adds a parse callback, to be invoked when option parsing is done.""" 260 self._parse_callbacks.append(stack_context.wrap(callback)) 261 262 def run_parse_callbacks(self): 263 for callback in self._parse_callbacks: 264 callback() 265 266 def mockable(self): 267 """Returns a wrapper around self that is compatible with 268 `mock.patch <unittest.mock.patch>`. 269 270 The `mock.patch <unittest.mock.patch>` function (included in 271 the standard library `unittest.mock` package since Python 3.3, 272 or in the third-party ``mock`` package for older versions of 273 Python) is incompatible with objects like ``options`` that 274 override ``__getattr__`` and ``__setattr__``. This function 275 returns an object that can be used with `mock.patch.object 276 <unittest.mock.patch.object>` to modify option values:: 277 278 with mock.patch.object(options.mockable(), 'name', value): 279 assert options.name == value 280 """ 281 return _Mockable(self) 282 283 284 class _Mockable(object): 285 """`mock.patch` compatible wrapper for `OptionParser`. 286 287 As of ``mock`` version 1.0.1, when an object uses ``__getattr__`` 288 hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete 289 the attribute it set instead of setting a new one (assuming that 290 the object does not catpure ``__setattr__``, so the patch 291 created a new attribute in ``__dict__``). 292 293 _Mockable's getattr and setattr pass through to the underlying 294 OptionParser, and delattr undoes the effect of a previous setattr. 295 """ 296 def __init__(self, options): 297 # Modify __dict__ directly to bypass __setattr__ 298 self.__dict__['_options'] = options 299 self.__dict__['_originals'] = {} 300 301 def __getattr__(self, name): 302 return getattr(self._options, name) 303 304 def __setattr__(self, name, value): 305 assert name not in self._originals, "don't reuse mockable objects" 306 self._originals[name] = getattr(self._options, name) 307 setattr(self._options, name, value) 308 309 def __delattr__(self, name): 310 setattr(self._options, name, self._originals.pop(name)) 311 312 313 class _Option(object): 314 def __init__(self, name, default=None, type=basestring_type, help=None, 315 metavar=None, multiple=False, file_name=None, group_name=None, 316 callback=None): 317 if default is None and multiple: 318 default = [] 319 self.name = name 320 self.type = type 321 self.help = help 322 self.metavar = metavar 323 self.multiple = multiple 324 self.file_name = file_name 325 self.group_name = group_name 326 self.callback = callback 327 self.default = default 328 self._value = None 329 330 def value(self): 331 return self.default if self._value is None else self._value 332 333 def parse(self, value): 334 _parse = { 335 datetime.datetime: self._parse_datetime, 336 datetime.timedelta: self._parse_timedelta, 337 bool: self._parse_bool, 338 basestring_type: self._parse_string, 339 }.get(self.type, self.type) 340 if self.multiple: 341 self._value = [] 342 for part in value.split(","): 343 if issubclass(self.type, numbers.Integral): 344 # allow ranges of the form X:Y (inclusive at both ends) 345 lo, _, hi = part.partition(":") 346 lo = _parse(lo) 347 hi = _parse(hi) if hi else lo 348 self._value.extend(range(lo, hi + 1)) 349 else: 350 self._value.append(_parse(part)) 351 else: 352 self._value = _parse(value) 353 if self.callback is not None: 354 self.callback(self._value) 355 return self.value() 356 357 def set(self, value): 358 if self.multiple: 359 if not isinstance(value, list): 360 raise Error("Option %r is required to be a list of %s" % 361 (self.name, self.type.__name__)) 362 for item in value: 363 if item != None and not isinstance(item, self.type): 364 raise Error("Option %r is required to be a list of %s" % 365 (self.name, self.type.__name__)) 366 else: 367 if value != None and not isinstance(value, self.type): 368 raise Error("Option %r is required to be a %s (%s given)" % 369 (self.name, self.type.__name__, type(value))) 370 self._value = value 371 if self.callback is not None: 372 self.callback(self._value) 373 374 # Supported date/time formats in our options 375 _DATETIME_FORMATS = [ 376 "%a %b %d %H:%M:%S %Y", 377 "%Y-%m-%d %H:%M:%S", 378 "%Y-%m-%d %H:%M", 379 "%Y-%m-%dT%H:%M", 380 "%Y%m%d %H:%M:%S", 381 "%Y%m%d %H:%M", 382 "%Y-%m-%d", 383 "%Y%m%d", 384 "%H:%M:%S", 385 "%H:%M", 386 ] 387 388 def _parse_datetime(self, value): 389 for format in self._DATETIME_FORMATS: 390 try: 391 return datetime.datetime.strptime(value, format) 392 except ValueError: 393 pass 394 raise Error('Unrecognized date/time format: %r' % value) 395 396 _TIMEDELTA_ABBREVS = [ 397 ('hours', ['h']), 398 ('minutes', ['m', 'min']), 399 ('seconds', ['s', 'sec']), 400 ('milliseconds', ['ms']), 401 ('microseconds', ['us']), 402 ('days', ['d']), 403 ('weeks', ['w']), 404 ] 405 406 _TIMEDELTA_ABBREV_DICT = dict( 407 (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS 408 for abbrev in abbrevs) 409 410 _FLOAT_PATTERN = r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?' 411 412 _TIMEDELTA_PATTERN = re.compile( 413 r'\s*(%s)\s*(\w*)\s*' % _FLOAT_PATTERN, re.IGNORECASE) 414 415 def _parse_timedelta(self, value): 416 try: 417 sum = datetime.timedelta() 418 start = 0 419 while start < len(value): 420 m = self._TIMEDELTA_PATTERN.match(value, start) 421 if not m: 422 raise Exception() 423 num = float(m.group(1)) 424 units = m.group(2) or 'seconds' 425 units = self._TIMEDELTA_ABBREV_DICT.get(units, units) 426 sum += datetime.timedelta(**{units: num}) 427 start = m.end() 428 return sum 429 except Exception: 430 raise 431 432 def _parse_bool(self, value): 433 return value.lower() not in ("false", "0", "f") 434 435 def _parse_string(self, value): 436 return _unicode(value) 437 438 439 options = OptionParser() 440 """Global options object. 441 442 All defined options are available as attributes on this object. 443 """ 444 445 446 def define(name, default=None, type=None, help=None, metavar=None, 447 multiple=False, group=None, callback=None): 448 """Defines an option in the global namespace. 449 450 See `OptionParser.define`. 451 """ 452 return options.define(name, default=default, type=type, help=help, 453 metavar=metavar, multiple=multiple, group=group, 454 callback=callback) 455 456 457 def parse_command_line(args=None, final=True): 458 """Parses global options from the command line. 459 460 See `OptionParser.parse_command_line`. 461 """ 462 return options.parse_command_line(args, final=final) 463 464 465 def parse_config_file(path, final=True): 466 """Parses global options from a config file. 467 468 See `OptionParser.parse_config_file`. 469 """ 470 return options.parse_config_file(path, final=final) 471 472 473 def print_help(file=None): 474 """Prints all the command line options to stderr (or another file). 475 476 See `OptionParser.print_help`. 477 """ 478 return options.print_help(file) 479 480 481 def add_parse_callback(callback): 482 """Adds a parse callback, to be invoked when option parsing is done. 483 484 See `OptionParser.add_parse_callback` 485 """ 486 options.add_parse_callback(callback) 487 488 489 # Default options 490 define_logging_options(options) 491 [end of tornado/options.py] </code> Please solve the feature request with adding the functions or classes between the <definitions> and </definitions>. You do not need to output any changes or edits for description files like .md or .rst files. I need you to make multiple edits across one or more files in a repository to implement a specific feature or improvement mentioned above. The edits should be output in patch format. Here is an example of a patch file. It consists of changes to the code base. It specifies the file names, the line numbers of each change, and the removed and added lines. A single patch file can contain changes to multiple files. <patch> diff --git a/src/code.py b/src/code.py --- a/src/code.py +++ b/src/code.py @@ -1,11 +1,14 @@ def factorial(a): + assert type(a) == int and a >= 0 res = 1 - while a >= 0: + while a >= 2: res *= a + a -= 1 return res # # # # def exact_dividion(x, y): + assert type(x) == type(y) == int and x > 0 and y > 0 return x % y == 0 diff --git a/src/demo.py b/src/demo.py new file mode 100644 --- /dev/null +++ b/src/demo.py @@ -0,0 +1,2 @@ +from code import factorial +print(factorial(5)) </patch> I need you to solve the provided feature request by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the format shown above. Respond below:
You will be provided with a partial code base and an feature request which requires a new feature to add in the code repository. <request> Make options instance more dict-like. In my Motor-Blog application, I find myself copying a lot of options from tornado.options into Application(). I thought this would be nice: application = Application(handler, **options.options.as_dict()) ... so I added as_dict() and some dict-like features to OptionParser. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in tornado/options.py] (definition of OptionParser.__iter__:) def __iter__(self): (definition of OptionParser.__getitem__:) def __getitem__(self, item): (definition of OptionParser.items:) def items(self): (definition of OptionParser.groups:) def groups(self): (definition of OptionParser.group_dict:) def group_dict(self, group): (definition of OptionParser.as_dict:) def as_dict(self): [end of new definitions in tornado/options.py] </definitions> All the involved readme files and code files are listed below with their contents. If a file's content is indicated as empty, it means that the file does not yet exist in the current repository and needs to be created with new content. <code> [start of tornado/options.py] #!/usr/bin/env python # # Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """A command line parsing module that lets modules define their own options. Each module defines its own options which are added to the global option namespace, e.g.:: from tornado.options import define, options define("mysql_host", default="127.0.0.1:3306", help="Main user DB") define("memcache_hosts", default="127.0.0.1:11011", multiple=True, help="Main user memcache servers") def connect(): db = database.Connection(options.mysql_host) ... The ``main()`` method of your application does not need to be aware of all of the options used throughout your program; they are all automatically loaded when the modules are loaded. However, all modules that define options must have been imported before the command line is parsed. Your ``main()`` method can parse the command line or parse a config file with either:: tornado.options.parse_command_line() # or tornado.options.parse_config_file("/etc/server.conf") Command line formats are what you would expect (``--myoption=myvalue``). Config files are just Python files. Global names become options, e.g.:: myoption = "myvalue" myotheroption = "myothervalue" We support `datetimes <datetime.datetime>`, `timedeltas <datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to `define`). We also accept multi-value options. See the documentation for `define()` below. `tornado.options.options` is a singleton instance of `OptionParser`, and the top-level functions in this module (`define`, `parse_command_line`, etc) simply call methods on it. You may create additional `OptionParser` instances to define isolated sets of options, such as for subcommands. """ from __future__ import absolute_import, division, print_function, with_statement import datetime import numbers import re import sys import os import textwrap from tornado.escape import _unicode from tornado.log import define_logging_options from tornado import stack_context from tornado.util import basestring_type, exec_in class Error(Exception): """Exception raised by errors in the options module.""" pass class OptionParser(object): """A collection of options, a dictionary with object-like access. Normally accessed via static functions in the `tornado.options` module, which reference a global instance. """ def __init__(self): # we have to use self.__dict__ because we override setattr. self.__dict__['_options'] = {} self.__dict__['_parse_callbacks'] = [] self.define("help", type=bool, help="show this help information", callback=self._help_callback) def __getattr__(self, name): if isinstance(self._options.get(name), _Option): return self._options[name].value() raise AttributeError("Unrecognized option %r" % name) def __setattr__(self, name, value): if isinstance(self._options.get(name), _Option): return self._options[name].set(value) raise AttributeError("Unrecognized option %r" % name) def define(self, name, default=None, type=None, help=None, metavar=None, multiple=False, group=None, callback=None): """Defines a new command line option. If ``type`` is given (one of str, float, int, datetime, or timedelta) or can be inferred from the ``default``, we parse the command line arguments based on the given type. If ``multiple`` is True, we accept comma-separated values, and the option value is always a list. For multi-value integers, we also accept the syntax ``x:y``, which turns into ``range(x, y)`` - very useful for long integer ranges. ``help`` and ``metavar`` are used to construct the automatically generated command line help string. The help message is formatted like:: --name=METAVAR help string ``group`` is used to group the defined options in logical groups. By default, command line options are grouped by the file in which they are defined. Command line option names must be unique globally. They can be parsed from the command line with `parse_command_line` or parsed from a config file with `parse_config_file`. If a ``callback`` is given, it will be run with the new value whenever the option is changed. This can be used to combine command-line and file-based options:: define("config", type=str, help="path to config file", callback=lambda path: parse_config_file(path, final=False)) With this definition, options in the file specified by ``--config`` will override options set earlier on the command line, but can be overridden by later flags. """ if name in self._options: raise Error("Option %r already defined in %s", name, self._options[name].file_name) frame = sys._getframe(0) options_file = frame.f_code.co_filename file_name = frame.f_back.f_code.co_filename if file_name == options_file: file_name = "" if type is None: if not multiple and default is not None: type = default.__class__ else: type = str if group: group_name = group else: group_name = file_name self._options[name] = _Option(name, file_name=file_name, default=default, type=type, help=help, metavar=metavar, multiple=multiple, group_name=group_name, callback=callback) def parse_command_line(self, args=None, final=True): """Parses all options given on the command line (defaults to `sys.argv`). Note that ``args[0]`` is ignored since it is the program name in `sys.argv`. We return a list of all arguments that are not parsed as options. If ``final`` is ``False``, parse callbacks will not be run. This is useful for applications that wish to combine configurations from multiple sources. """ if args is None: args = sys.argv remaining = [] for i in range(1, len(args)): # All things after the last option are command line arguments if not args[i].startswith("-"): remaining = args[i:] break if args[i] == "--": remaining = args[i + 1:] break arg = args[i].lstrip("-") name, equals, value = arg.partition("=") name = name.replace('-', '_') if not name in self._options: self.print_help() raise Error('Unrecognized command line option: %r' % name) option = self._options[name] if not equals: if option.type == bool: value = "true" else: raise Error('Option %r requires a value' % name) option.parse(value) if final: self.run_parse_callbacks() return remaining def parse_config_file(self, path, final=True): """Parses and loads the Python config file at the given path. If ``final`` is ``False``, parse callbacks will not be run. This is useful for applications that wish to combine configurations from multiple sources. """ config = {} with open(path) as f: exec_in(f.read(), config, config) for name in config: if name in self._options: self._options[name].set(config[name]) if final: self.run_parse_callbacks() def print_help(self, file=None): """Prints all the command line options to stderr (or another file).""" if file is None: file = sys.stderr print("Usage: %s [OPTIONS]" % sys.argv[0], file=file) print("\nOptions:\n", file=file) by_group = {} for option in self._options.values(): by_group.setdefault(option.group_name, []).append(option) for filename, o in sorted(by_group.items()): if filename: print("\n%s options:\n" % os.path.normpath(filename), file=file) o.sort(key=lambda option: option.name) for option in o: prefix = option.name if option.metavar: prefix += "=" + option.metavar description = option.help or "" if option.default is not None and option.default != '': description += " (default %s)" % option.default lines = textwrap.wrap(description, 79 - 35) if len(prefix) > 30 or len(lines) == 0: lines.insert(0, '') print(" --%-30s %s" % (prefix, lines[0]), file=file) for line in lines[1:]: print("%-34s %s" % (' ', line), file=file) print(file=file) def _help_callback(self, value): if value: self.print_help() sys.exit(0) def add_parse_callback(self, callback): """Adds a parse callback, to be invoked when option parsing is done.""" self._parse_callbacks.append(stack_context.wrap(callback)) def run_parse_callbacks(self): for callback in self._parse_callbacks: callback() def mockable(self): """Returns a wrapper around self that is compatible with `mock.patch <unittest.mock.patch>`. The `mock.patch <unittest.mock.patch>` function (included in the standard library `unittest.mock` package since Python 3.3, or in the third-party ``mock`` package for older versions of Python) is incompatible with objects like ``options`` that override ``__getattr__`` and ``__setattr__``. This function returns an object that can be used with `mock.patch.object <unittest.mock.patch.object>` to modify option values:: with mock.patch.object(options.mockable(), 'name', value): assert options.name == value """ return _Mockable(self) class _Mockable(object): """`mock.patch` compatible wrapper for `OptionParser`. As of ``mock`` version 1.0.1, when an object uses ``__getattr__`` hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete the attribute it set instead of setting a new one (assuming that the object does not catpure ``__setattr__``, so the patch created a new attribute in ``__dict__``). _Mockable's getattr and setattr pass through to the underlying OptionParser, and delattr undoes the effect of a previous setattr. """ def __init__(self, options): # Modify __dict__ directly to bypass __setattr__ self.__dict__['_options'] = options self.__dict__['_originals'] = {} def __getattr__(self, name): return getattr(self._options, name) def __setattr__(self, name, value): assert name not in self._originals, "don't reuse mockable objects" self._originals[name] = getattr(self._options, name) setattr(self._options, name, value) def __delattr__(self, name): setattr(self._options, name, self._originals.pop(name)) class _Option(object): def __init__(self, name, default=None, type=basestring_type, help=None, metavar=None, multiple=False, file_name=None, group_name=None, callback=None): if default is None and multiple: default = [] self.name = name self.type = type self.help = help self.metavar = metavar self.multiple = multiple self.file_name = file_name self.group_name = group_name self.callback = callback self.default = default self._value = None def value(self): return self.default if self._value is None else self._value def parse(self, value): _parse = { datetime.datetime: self._parse_datetime, datetime.timedelta: self._parse_timedelta, bool: self._parse_bool, basestring_type: self._parse_string, }.get(self.type, self.type) if self.multiple: self._value = [] for part in value.split(","): if issubclass(self.type, numbers.Integral): # allow ranges of the form X:Y (inclusive at both ends) lo, _, hi = part.partition(":") lo = _parse(lo) hi = _parse(hi) if hi else lo self._value.extend(range(lo, hi + 1)) else: self._value.append(_parse(part)) else: self._value = _parse(value) if self.callback is not None: self.callback(self._value) return self.value() def set(self, value): if self.multiple: if not isinstance(value, list): raise Error("Option %r is required to be a list of %s" % (self.name, self.type.__name__)) for item in value: if item != None and not isinstance(item, self.type): raise Error("Option %r is required to be a list of %s" % (self.name, self.type.__name__)) else: if value != None and not isinstance(value, self.type): raise Error("Option %r is required to be a %s (%s given)" % (self.name, self.type.__name__, type(value))) self._value = value if self.callback is not None: self.callback(self._value) # Supported date/time formats in our options _DATETIME_FORMATS = [ "%a %b %d %H:%M:%S %Y", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y%m%d %H:%M:%S", "%Y%m%d %H:%M", "%Y-%m-%d", "%Y%m%d", "%H:%M:%S", "%H:%M", ] def _parse_datetime(self, value): for format in self._DATETIME_FORMATS: try: return datetime.datetime.strptime(value, format) except ValueError: pass raise Error('Unrecognized date/time format: %r' % value) _TIMEDELTA_ABBREVS = [ ('hours', ['h']), ('minutes', ['m', 'min']), ('seconds', ['s', 'sec']), ('milliseconds', ['ms']), ('microseconds', ['us']), ('days', ['d']), ('weeks', ['w']), ] _TIMEDELTA_ABBREV_DICT = dict( (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS for abbrev in abbrevs) _FLOAT_PATTERN = r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?' _TIMEDELTA_PATTERN = re.compile( r'\s*(%s)\s*(\w*)\s*' % _FLOAT_PATTERN, re.IGNORECASE) def _parse_timedelta(self, value): try: sum = datetime.timedelta() start = 0 while start < len(value): m = self._TIMEDELTA_PATTERN.match(value, start) if not m: raise Exception() num = float(m.group(1)) units = m.group(2) or 'seconds' units = self._TIMEDELTA_ABBREV_DICT.get(units, units) sum += datetime.timedelta(**{units: num}) start = m.end() return sum except Exception: raise def _parse_bool(self, value): return value.lower() not in ("false", "0", "f") def _parse_string(self, value): return _unicode(value) options = OptionParser() """Global options object. All defined options are available as attributes on this object. """ def define(name, default=None, type=None, help=None, metavar=None, multiple=False, group=None, callback=None): """Defines an option in the global namespace. See `OptionParser.define`. """ return options.define(name, default=default, type=type, help=help, metavar=metavar, multiple=multiple, group=group, callback=callback) def parse_command_line(args=None, final=True): """Parses global options from the command line. See `OptionParser.parse_command_line`. """ return options.parse_command_line(args, final=final) def parse_config_file(path, final=True): """Parses global options from a config file. See `OptionParser.parse_config_file`. """ return options.parse_config_file(path, final=final) def print_help(file=None): """Prints all the command line options to stderr (or another file). See `OptionParser.print_help`. """ return options.print_help(file) def add_parse_callback(callback): """Adds a parse callback, to be invoked when option parsing is done. See `OptionParser.add_parse_callback` """ options.add_parse_callback(callback) # Default options define_logging_options(options) [end of tornado/options.py] </code> Please solve the feature request with adding the functions or classes between the <definitions> and </definitions>. You do not need to output any changes or edits for description files like .md or .rst files. I need you to make multiple edits across one or more files in a repository to implement a specific feature or improvement mentioned above. For each edit, output the changes in the following format: ``` <edit> [start of the snippet before editing in <file_path>] <code_before_edit> [end of the snippet before editing in <file_path>] [start of the snippet after editing in <file_path>] <code_after_edit> [end of the snippet after editing in <file_path>] </edit> ``` Notes: - The <file_path> is the relative path of the file being edited. - The <code_before_edit> snippet should include several lines before and after the modified region, unless the file was originally empty. - If a file was originally empty, leave <code_before_edit> blank but ensure <code_after_edit> includes the new content. - Ensure the edits are sequential and address all necessary changes to achieve the requested feature. Here is an example of the output format: ``` <edit> [start of the snippet before editing in src/code.py] def factorial(a): res = 1 while a >= 0: res *= a return res [end of the snippet before editing in src/code.py] [start of the snippet after editing in src/code.py] def factorial(a): assert type(a) == int and a >= 0 res = 1 while a >= 2: res *= a a -= 1 return res [end of the snippet after editing in src/code.py] </edit> <edit> [start of the snippet before editing in src/code.py] def exact_dividion(x, y): return x % y == 0 [end of the snippet before editing in src/code.py] [start of the snippet after editing in src/code.py] def exact_dividion(x, y): assert type(x) == type(y) == int and x > 0 and y > 0 return x % y == 0 [end of the snippet after editing in src/code.py] </edit> <edit> [start of the snippet before editing in src/demo.py] [end of the snippet before editing in src/demo.py] [start of the snippet after editing in src/demo.py] from code import factorial print(factorial(5)) [end of the snippet after editing in src/demo.py] </edit> ``` I need you to solve the feature request with a series of edits in the format shown above. Respond below: