OLD | NEW |
1 """Utilities for writing code that runs on Python 2 and 3""" | |
2 | |
3 # Copyright (c) 2010-2015 Benjamin Peterson | 1 # Copyright (c) 2010-2015 Benjamin Peterson |
4 # | 2 # |
5 # Permission is hereby granted, free of charge, to any person obtaining a copy | 3 # Permission is hereby granted, free of charge, to any person obtaining a copy |
6 # of this software and associated documentation files (the "Software"), to deal | 4 # of this software and associated documentation files (the "Software"), to deal |
7 # in the Software without restriction, including without limitation the rights | 5 # in the Software without restriction, including without limitation the rights |
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | 6 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
9 # copies of the Software, and to permit persons to whom the Software is | 7 # copies of the Software, and to permit persons to whom the Software is |
10 # furnished to do so, subject to the following conditions: | 8 # furnished to do so, subject to the following conditions: |
11 # | 9 # |
12 # The above copyright notice and this permission notice shall be included in all | 10 # The above copyright notice and this permission notice shall be included in all |
13 # copies or substantial portions of the Software. | 11 # copies or substantial portions of the Software. |
14 # | 12 # |
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | 13 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | 14 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | 15 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | 16 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | 17 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | 18 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
21 # SOFTWARE. | 19 # SOFTWARE. |
22 | 20 |
| 21 """Utilities for writing code that runs on Python 2 and 3""" |
| 22 |
23 from __future__ import absolute_import | 23 from __future__ import absolute_import |
24 | 24 |
25 import functools | 25 import functools |
26 import itertools | 26 import itertools |
27 import operator | 27 import operator |
28 import sys | 28 import sys |
29 import types | 29 import types |
30 | 30 |
31 __author__ = "Benjamin Peterson <benjamin@python.org>" | 31 __author__ = "Benjamin Peterson <benjamin@python.org>" |
32 __version__ = "1.9.0" | 32 __version__ = "1.10.0" |
33 | 33 |
34 | 34 |
35 # Useful for very coarse version differentiation. | 35 # Useful for very coarse version differentiation. |
36 PY2 = sys.version_info[0] == 2 | 36 PY2 = sys.version_info[0] == 2 |
37 PY3 = sys.version_info[0] == 3 | 37 PY3 = sys.version_info[0] == 3 |
| 38 PY34 = sys.version_info[0:2] >= (3, 4) |
38 | 39 |
39 if PY3: | 40 if PY3: |
40 string_types = str, | 41 string_types = str, |
41 integer_types = int, | 42 integer_types = int, |
42 class_types = type, | 43 class_types = type, |
43 text_type = str | 44 text_type = str |
44 binary_type = bytes | 45 binary_type = bytes |
45 | 46 |
46 MAXSIZE = sys.maxsize | 47 MAXSIZE = sys.maxsize |
47 else: | 48 else: |
48 string_types = basestring, | 49 string_types = basestring, |
49 integer_types = (int, long) | 50 integer_types = (int, long) |
50 class_types = (type, types.ClassType) | 51 class_types = (type, types.ClassType) |
51 text_type = unicode | 52 text_type = unicode |
52 binary_type = str | 53 binary_type = str |
53 | 54 |
54 if sys.platform.startswith("java"): | 55 if sys.platform.startswith("java"): |
55 # Jython always uses 32 bits. | 56 # Jython always uses 32 bits. |
56 MAXSIZE = int((1 << 31) - 1) | 57 MAXSIZE = int((1 << 31) - 1) |
57 else: | 58 else: |
58 # It's possible to have sizeof(long) != sizeof(Py_ssize_t). | 59 # It's possible to have sizeof(long) != sizeof(Py_ssize_t). |
59 class X(object): | 60 class X(object): |
| 61 |
60 def __len__(self): | 62 def __len__(self): |
61 return 1 << 31 | 63 return 1 << 31 |
62 try: | 64 try: |
63 len(X()) | 65 len(X()) |
64 except OverflowError: | 66 except OverflowError: |
65 # 32-bit | 67 # 32-bit |
66 MAXSIZE = int((1 << 31) - 1) | 68 MAXSIZE = int((1 << 31) - 1) |
67 else: | 69 else: |
68 # 64-bit | 70 # 64-bit |
69 MAXSIZE = int((1 << 63) - 1) | 71 MAXSIZE = int((1 << 63) - 1) |
(...skipping 11 matching lines...) Expand all Loading... |
81 return sys.modules[name] | 83 return sys.modules[name] |
82 | 84 |
83 | 85 |
84 class _LazyDescr(object): | 86 class _LazyDescr(object): |
85 | 87 |
86 def __init__(self, name): | 88 def __init__(self, name): |
87 self.name = name | 89 self.name = name |
88 | 90 |
89 def __get__(self, obj, tp): | 91 def __get__(self, obj, tp): |
90 result = self._resolve() | 92 result = self._resolve() |
91 setattr(obj, self.name, result) # Invokes __set__. | 93 setattr(obj, self.name, result) # Invokes __set__. |
92 try: | 94 try: |
93 # This is a bit ugly, but it avoids running this again by | 95 # This is a bit ugly, but it avoids running this again by |
94 # removing this descriptor. | 96 # removing this descriptor. |
95 delattr(obj.__class__, self.name) | 97 delattr(obj.__class__, self.name) |
96 except AttributeError: | 98 except AttributeError: |
97 pass | 99 pass |
98 return result | 100 return result |
99 | 101 |
100 | 102 |
101 class MovedModule(_LazyDescr): | 103 class MovedModule(_LazyDescr): |
(...skipping 51 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
153 if old_attr is None: | 155 if old_attr is None: |
154 old_attr = name | 156 old_attr = name |
155 self.attr = old_attr | 157 self.attr = old_attr |
156 | 158 |
157 def _resolve(self): | 159 def _resolve(self): |
158 module = _import_module(self.mod) | 160 module = _import_module(self.mod) |
159 return getattr(module, self.attr) | 161 return getattr(module, self.attr) |
160 | 162 |
161 | 163 |
162 class _SixMetaPathImporter(object): | 164 class _SixMetaPathImporter(object): |
| 165 |
163 """ | 166 """ |
164 A meta path importer to import six.moves and its submodules. | 167 A meta path importer to import six.moves and its submodules. |
165 | 168 |
166 This class implements a PEP302 finder and loader. It should be compatible | 169 This class implements a PEP302 finder and loader. It should be compatible |
167 with Python 2.5 and all existing versions of Python3 | 170 with Python 2.5 and all existing versions of Python3 |
168 """ | 171 """ |
| 172 |
169 def __init__(self, six_module_name): | 173 def __init__(self, six_module_name): |
170 self.name = six_module_name | 174 self.name = six_module_name |
171 self.known_modules = {} | 175 self.known_modules = {} |
172 | 176 |
173 def _add_module(self, mod, *fullnames): | 177 def _add_module(self, mod, *fullnames): |
174 for fullname in fullnames: | 178 for fullname in fullnames: |
175 self.known_modules[self.name + "." + fullname] = mod | 179 self.known_modules[self.name + "." + fullname] = mod |
176 | 180 |
177 def _get_module(self, fullname): | 181 def _get_module(self, fullname): |
178 return self.known_modules[self.name + "." + fullname] | 182 return self.known_modules[self.name + "." + fullname] |
(...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
216 | 220 |
217 Required, if is_package is implemented""" | 221 Required, if is_package is implemented""" |
218 self.__get_module(fullname) # eventually raises ImportError | 222 self.__get_module(fullname) # eventually raises ImportError |
219 return None | 223 return None |
220 get_source = get_code # same as get_code | 224 get_source = get_code # same as get_code |
221 | 225 |
222 _importer = _SixMetaPathImporter(__name__) | 226 _importer = _SixMetaPathImporter(__name__) |
223 | 227 |
224 | 228 |
225 class _MovedItems(_LazyModule): | 229 class _MovedItems(_LazyModule): |
| 230 |
226 """Lazy loading of moved objects""" | 231 """Lazy loading of moved objects""" |
227 __path__ = [] # mark as package | 232 __path__ = [] # mark as package |
228 | 233 |
229 | 234 |
230 _moved_attributes = [ | 235 _moved_attributes = [ |
231 MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), | 236 MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), |
232 MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), | 237 MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), |
233 MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "fil
terfalse"), | 238 MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "fil
terfalse"), |
234 MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), | 239 MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), |
235 MovedAttribute("intern", "__builtin__", "sys"), | 240 MovedAttribute("intern", "__builtin__", "sys"), |
236 MovedAttribute("map", "itertools", "builtins", "imap", "map"), | 241 MovedAttribute("map", "itertools", "builtins", "imap", "map"), |
| 242 MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), |
| 243 MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), |
237 MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), | 244 MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), |
238 MovedAttribute("reload_module", "__builtin__", "imp", "reload"), | 245 MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp
", "reload"), |
239 MovedAttribute("reduce", "__builtin__", "functools"), | 246 MovedAttribute("reduce", "__builtin__", "functools"), |
240 MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), | 247 MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), |
241 MovedAttribute("StringIO", "StringIO", "io"), | 248 MovedAttribute("StringIO", "StringIO", "io"), |
242 MovedAttribute("UserDict", "UserDict", "collections"), | 249 MovedAttribute("UserDict", "UserDict", "collections"), |
243 MovedAttribute("UserList", "UserList", "collections"), | 250 MovedAttribute("UserList", "UserList", "collections"), |
244 MovedAttribute("UserString", "UserString", "collections"), | 251 MovedAttribute("UserString", "UserString", "collections"), |
245 MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), | 252 MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), |
246 MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), | 253 MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), |
247 MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip
_longest"), | 254 MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip
_longest"), |
248 | |
249 MovedModule("builtins", "__builtin__"), | 255 MovedModule("builtins", "__builtin__"), |
250 MovedModule("configparser", "ConfigParser"), | 256 MovedModule("configparser", "ConfigParser"), |
251 MovedModule("copyreg", "copy_reg"), | 257 MovedModule("copyreg", "copy_reg"), |
252 MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), | 258 MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), |
253 MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), | 259 MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), |
254 MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), | 260 MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), |
255 MovedModule("http_cookies", "Cookie", "http.cookies"), | 261 MovedModule("http_cookies", "Cookie", "http.cookies"), |
256 MovedModule("html_entities", "htmlentitydefs", "html.entities"), | 262 MovedModule("html_entities", "htmlentitydefs", "html.entities"), |
257 MovedModule("html_parser", "HTMLParser", "html.parser"), | 263 MovedModule("html_parser", "HTMLParser", "html.parser"), |
258 MovedModule("http_client", "httplib", "http.client"), | 264 MovedModule("http_client", "httplib", "http.client"), |
(...skipping 26 matching lines...) Expand all Loading... |
285 MovedModule("tkinter_font", "tkFont", "tkinter.font"), | 291 MovedModule("tkinter_font", "tkFont", "tkinter.font"), |
286 MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), | 292 MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), |
287 MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", | 293 MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", |
288 "tkinter.simpledialog"), | 294 "tkinter.simpledialog"), |
289 MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"
), | 295 MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"
), |
290 MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"
), | 296 MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"
), |
291 MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"
), | 297 MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"
), |
292 MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), | 298 MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), |
293 MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), | 299 MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), |
294 MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), | 300 MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), |
295 MovedModule("winreg", "_winreg"), | |
296 ] | 301 ] |
| 302 # Add windows specific modules. |
| 303 if sys.platform == "win32": |
| 304 _moved_attributes += [ |
| 305 MovedModule("winreg", "_winreg"), |
| 306 ] |
| 307 |
297 for attr in _moved_attributes: | 308 for attr in _moved_attributes: |
298 setattr(_MovedItems, attr.name, attr) | 309 setattr(_MovedItems, attr.name, attr) |
299 if isinstance(attr, MovedModule): | 310 if isinstance(attr, MovedModule): |
300 _importer._add_module(attr, "moves." + attr.name) | 311 _importer._add_module(attr, "moves." + attr.name) |
301 del attr | 312 del attr |
302 | 313 |
303 _MovedItems._moved_attributes = _moved_attributes | 314 _MovedItems._moved_attributes = _moved_attributes |
304 | 315 |
305 moves = _MovedItems(__name__ + ".moves") | 316 moves = _MovedItems(__name__ + ".moves") |
306 _importer._add_module(moves, "moves") | 317 _importer._add_module(moves, "moves") |
307 | 318 |
308 | 319 |
309 class Module_six_moves_urllib_parse(_LazyModule): | 320 class Module_six_moves_urllib_parse(_LazyModule): |
| 321 |
310 """Lazy loading of moved objects in six.moves.urllib_parse""" | 322 """Lazy loading of moved objects in six.moves.urllib_parse""" |
311 | 323 |
312 | 324 |
313 _urllib_parse_moved_attributes = [ | 325 _urllib_parse_moved_attributes = [ |
314 MovedAttribute("ParseResult", "urlparse", "urllib.parse"), | 326 MovedAttribute("ParseResult", "urlparse", "urllib.parse"), |
315 MovedAttribute("SplitResult", "urlparse", "urllib.parse"), | 327 MovedAttribute("SplitResult", "urlparse", "urllib.parse"), |
316 MovedAttribute("parse_qs", "urlparse", "urllib.parse"), | 328 MovedAttribute("parse_qs", "urlparse", "urllib.parse"), |
317 MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), | 329 MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), |
318 MovedAttribute("urldefrag", "urlparse", "urllib.parse"), | 330 MovedAttribute("urldefrag", "urlparse", "urllib.parse"), |
319 MovedAttribute("urljoin", "urlparse", "urllib.parse"), | 331 MovedAttribute("urljoin", "urlparse", "urllib.parse"), |
(...skipping 19 matching lines...) Expand all Loading... |
339 setattr(Module_six_moves_urllib_parse, attr.name, attr) | 351 setattr(Module_six_moves_urllib_parse, attr.name, attr) |
340 del attr | 352 del attr |
341 | 353 |
342 Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes | 354 Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes |
343 | 355 |
344 _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_pa
rse"), | 356 _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_pa
rse"), |
345 "moves.urllib_parse", "moves.urllib.parse") | 357 "moves.urllib_parse", "moves.urllib.parse") |
346 | 358 |
347 | 359 |
348 class Module_six_moves_urllib_error(_LazyModule): | 360 class Module_six_moves_urllib_error(_LazyModule): |
| 361 |
349 """Lazy loading of moved objects in six.moves.urllib_error""" | 362 """Lazy loading of moved objects in six.moves.urllib_error""" |
350 | 363 |
351 | 364 |
352 _urllib_error_moved_attributes = [ | 365 _urllib_error_moved_attributes = [ |
353 MovedAttribute("URLError", "urllib2", "urllib.error"), | 366 MovedAttribute("URLError", "urllib2", "urllib.error"), |
354 MovedAttribute("HTTPError", "urllib2", "urllib.error"), | 367 MovedAttribute("HTTPError", "urllib2", "urllib.error"), |
355 MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), | 368 MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), |
356 ] | 369 ] |
357 for attr in _urllib_error_moved_attributes: | 370 for attr in _urllib_error_moved_attributes: |
358 setattr(Module_six_moves_urllib_error, attr.name, attr) | 371 setattr(Module_six_moves_urllib_error, attr.name, attr) |
359 del attr | 372 del attr |
360 | 373 |
361 Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes | 374 Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes |
362 | 375 |
363 _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.er
ror"), | 376 _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.er
ror"), |
364 "moves.urllib_error", "moves.urllib.error") | 377 "moves.urllib_error", "moves.urllib.error") |
365 | 378 |
366 | 379 |
367 class Module_six_moves_urllib_request(_LazyModule): | 380 class Module_six_moves_urllib_request(_LazyModule): |
| 381 |
368 """Lazy loading of moved objects in six.moves.urllib_request""" | 382 """Lazy loading of moved objects in six.moves.urllib_request""" |
369 | 383 |
370 | 384 |
371 _urllib_request_moved_attributes = [ | 385 _urllib_request_moved_attributes = [ |
372 MovedAttribute("urlopen", "urllib2", "urllib.request"), | 386 MovedAttribute("urlopen", "urllib2", "urllib.request"), |
373 MovedAttribute("install_opener", "urllib2", "urllib.request"), | 387 MovedAttribute("install_opener", "urllib2", "urllib.request"), |
374 MovedAttribute("build_opener", "urllib2", "urllib.request"), | 388 MovedAttribute("build_opener", "urllib2", "urllib.request"), |
375 MovedAttribute("pathname2url", "urllib", "urllib.request"), | 389 MovedAttribute("pathname2url", "urllib", "urllib.request"), |
376 MovedAttribute("url2pathname", "urllib", "urllib.request"), | 390 MovedAttribute("url2pathname", "urllib", "urllib.request"), |
377 MovedAttribute("getproxies", "urllib", "urllib.request"), | 391 MovedAttribute("getproxies", "urllib", "urllib.request"), |
(...skipping 29 matching lines...) Expand all Loading... |
407 setattr(Module_six_moves_urllib_request, attr.name, attr) | 421 setattr(Module_six_moves_urllib_request, attr.name, attr) |
408 del attr | 422 del attr |
409 | 423 |
410 Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attrib
utes | 424 Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attrib
utes |
411 | 425 |
412 _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.
request"), | 426 _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.
request"), |
413 "moves.urllib_request", "moves.urllib.request") | 427 "moves.urllib_request", "moves.urllib.request") |
414 | 428 |
415 | 429 |
416 class Module_six_moves_urllib_response(_LazyModule): | 430 class Module_six_moves_urllib_response(_LazyModule): |
| 431 |
417 """Lazy loading of moved objects in six.moves.urllib_response""" | 432 """Lazy loading of moved objects in six.moves.urllib_response""" |
418 | 433 |
419 | 434 |
420 _urllib_response_moved_attributes = [ | 435 _urllib_response_moved_attributes = [ |
421 MovedAttribute("addbase", "urllib", "urllib.response"), | 436 MovedAttribute("addbase", "urllib", "urllib.response"), |
422 MovedAttribute("addclosehook", "urllib", "urllib.response"), | 437 MovedAttribute("addclosehook", "urllib", "urllib.response"), |
423 MovedAttribute("addinfo", "urllib", "urllib.response"), | 438 MovedAttribute("addinfo", "urllib", "urllib.response"), |
424 MovedAttribute("addinfourl", "urllib", "urllib.response"), | 439 MovedAttribute("addinfourl", "urllib", "urllib.response"), |
425 ] | 440 ] |
426 for attr in _urllib_response_moved_attributes: | 441 for attr in _urllib_response_moved_attributes: |
427 setattr(Module_six_moves_urllib_response, attr.name, attr) | 442 setattr(Module_six_moves_urllib_response, attr.name, attr) |
428 del attr | 443 del attr |
429 | 444 |
430 Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attr
ibutes | 445 Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attr
ibutes |
431 | 446 |
432 _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib
.response"), | 447 _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib
.response"), |
433 "moves.urllib_response", "moves.urllib.response") | 448 "moves.urllib_response", "moves.urllib.response") |
434 | 449 |
435 | 450 |
436 class Module_six_moves_urllib_robotparser(_LazyModule): | 451 class Module_six_moves_urllib_robotparser(_LazyModule): |
| 452 |
437 """Lazy loading of moved objects in six.moves.urllib_robotparser""" | 453 """Lazy loading of moved objects in six.moves.urllib_robotparser""" |
438 | 454 |
439 | 455 |
440 _urllib_robotparser_moved_attributes = [ | 456 _urllib_robotparser_moved_attributes = [ |
441 MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), | 457 MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), |
442 ] | 458 ] |
443 for attr in _urllib_robotparser_moved_attributes: | 459 for attr in _urllib_robotparser_moved_attributes: |
444 setattr(Module_six_moves_urllib_robotparser, attr.name, attr) | 460 setattr(Module_six_moves_urllib_robotparser, attr.name, attr) |
445 del attr | 461 del attr |
446 | 462 |
447 Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_move
d_attributes | 463 Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_move
d_attributes |
448 | 464 |
449 _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.url
lib.robotparser"), | 465 _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.url
lib.robotparser"), |
450 "moves.urllib_robotparser", "moves.urllib.robotparser") | 466 "moves.urllib_robotparser", "moves.urllib.robotparser") |
451 | 467 |
452 | 468 |
453 class Module_six_moves_urllib(types.ModuleType): | 469 class Module_six_moves_urllib(types.ModuleType): |
| 470 |
454 """Create a six.moves.urllib namespace that resembles the Python 3 namespace
""" | 471 """Create a six.moves.urllib namespace that resembles the Python 3 namespace
""" |
455 __path__ = [] # mark as package | 472 __path__ = [] # mark as package |
456 parse = _importer._get_module("moves.urllib_parse") | 473 parse = _importer._get_module("moves.urllib_parse") |
457 error = _importer._get_module("moves.urllib_error") | 474 error = _importer._get_module("moves.urllib_error") |
458 request = _importer._get_module("moves.urllib_request") | 475 request = _importer._get_module("moves.urllib_request") |
459 response = _importer._get_module("moves.urllib_response") | 476 response = _importer._get_module("moves.urllib_response") |
460 robotparser = _importer._get_module("moves.urllib_robotparser") | 477 robotparser = _importer._get_module("moves.urllib_robotparser") |
461 | 478 |
462 def __dir__(self): | 479 def __dir__(self): |
463 return ['parse', 'error', 'request', 'response', 'robotparser'] | 480 return ['parse', 'error', 'request', 'response', 'robotparser'] |
(...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
514 def callable(obj): | 531 def callable(obj): |
515 return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) | 532 return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) |
516 | 533 |
517 | 534 |
518 if PY3: | 535 if PY3: |
519 def get_unbound_function(unbound): | 536 def get_unbound_function(unbound): |
520 return unbound | 537 return unbound |
521 | 538 |
522 create_bound_method = types.MethodType | 539 create_bound_method = types.MethodType |
523 | 540 |
| 541 def create_unbound_method(func, cls): |
| 542 return func |
| 543 |
524 Iterator = object | 544 Iterator = object |
525 else: | 545 else: |
526 def get_unbound_function(unbound): | 546 def get_unbound_function(unbound): |
527 return unbound.im_func | 547 return unbound.im_func |
528 | 548 |
529 def create_bound_method(func, obj): | 549 def create_bound_method(func, obj): |
530 return types.MethodType(func, obj, obj.__class__) | 550 return types.MethodType(func, obj, obj.__class__) |
531 | 551 |
| 552 def create_unbound_method(func, cls): |
| 553 return types.MethodType(func, None, cls) |
| 554 |
532 class Iterator(object): | 555 class Iterator(object): |
533 | 556 |
534 def next(self): | 557 def next(self): |
535 return type(self).__next__(self) | 558 return type(self).__next__(self) |
536 | 559 |
537 callable = callable | 560 callable = callable |
538 _add_doc(get_unbound_function, | 561 _add_doc(get_unbound_function, |
539 """Get the function out of a possibly unbound function""") | 562 """Get the function out of a possibly unbound function""") |
540 | 563 |
541 | 564 |
(...skipping 18 matching lines...) Expand all Loading... |
560 def iterlists(d, **kw): | 583 def iterlists(d, **kw): |
561 return iter(d.lists(**kw)) | 584 return iter(d.lists(**kw)) |
562 | 585 |
563 viewkeys = operator.methodcaller("keys") | 586 viewkeys = operator.methodcaller("keys") |
564 | 587 |
565 viewvalues = operator.methodcaller("values") | 588 viewvalues = operator.methodcaller("values") |
566 | 589 |
567 viewitems = operator.methodcaller("items") | 590 viewitems = operator.methodcaller("items") |
568 else: | 591 else: |
569 def iterkeys(d, **kw): | 592 def iterkeys(d, **kw): |
570 return iter(d.iterkeys(**kw)) | 593 return d.iterkeys(**kw) |
571 | 594 |
572 def itervalues(d, **kw): | 595 def itervalues(d, **kw): |
573 return iter(d.itervalues(**kw)) | 596 return d.itervalues(**kw) |
574 | 597 |
575 def iteritems(d, **kw): | 598 def iteritems(d, **kw): |
576 return iter(d.iteritems(**kw)) | 599 return d.iteritems(**kw) |
577 | 600 |
578 def iterlists(d, **kw): | 601 def iterlists(d, **kw): |
579 return iter(d.iterlists(**kw)) | 602 return d.iterlists(**kw) |
580 | 603 |
581 viewkeys = operator.methodcaller("viewkeys") | 604 viewkeys = operator.methodcaller("viewkeys") |
582 | 605 |
583 viewvalues = operator.methodcaller("viewvalues") | 606 viewvalues = operator.methodcaller("viewvalues") |
584 | 607 |
585 viewitems = operator.methodcaller("viewitems") | 608 viewitems = operator.methodcaller("viewitems") |
586 | 609 |
587 _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") | 610 _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") |
588 _add_doc(itervalues, "Return an iterator over the values of a dictionary.") | 611 _add_doc(itervalues, "Return an iterator over the values of a dictionary.") |
589 _add_doc(iteritems, | 612 _add_doc(iteritems, |
590 "Return an iterator over the (key, value) pairs of a dictionary.") | 613 "Return an iterator over the (key, value) pairs of a dictionary.") |
591 _add_doc(iterlists, | 614 _add_doc(iterlists, |
592 "Return an iterator over the (key, [values]) pairs of a dictionary.") | 615 "Return an iterator over the (key, [values]) pairs of a dictionary.") |
593 | 616 |
594 | 617 |
595 if PY3: | 618 if PY3: |
596 def b(s): | 619 def b(s): |
597 return s.encode("latin-1") | 620 return s.encode("latin-1") |
| 621 |
598 def u(s): | 622 def u(s): |
599 return s | 623 return s |
600 unichr = chr | 624 unichr = chr |
601 if sys.version_info[1] <= 1: | 625 import struct |
602 def int2byte(i): | 626 int2byte = struct.Struct(">B").pack |
603 return bytes((i,)) | 627 del struct |
604 else: | |
605 # This is about 2x faster than the implementation above on 3.2+ | |
606 int2byte = operator.methodcaller("to_bytes", 1, "big") | |
607 byte2int = operator.itemgetter(0) | 628 byte2int = operator.itemgetter(0) |
608 indexbytes = operator.getitem | 629 indexbytes = operator.getitem |
609 iterbytes = iter | 630 iterbytes = iter |
610 import io | 631 import io |
611 StringIO = io.StringIO | 632 StringIO = io.StringIO |
612 BytesIO = io.BytesIO | 633 BytesIO = io.BytesIO |
613 _assertCountEqual = "assertCountEqual" | 634 _assertCountEqual = "assertCountEqual" |
614 _assertRaisesRegex = "assertRaisesRegex" | 635 if sys.version_info[1] <= 1: |
615 _assertRegex = "assertRegex" | 636 _assertRaisesRegex = "assertRaisesRegexp" |
| 637 _assertRegex = "assertRegexpMatches" |
| 638 else: |
| 639 _assertRaisesRegex = "assertRaisesRegex" |
| 640 _assertRegex = "assertRegex" |
616 else: | 641 else: |
617 def b(s): | 642 def b(s): |
618 return s | 643 return s |
619 # Workaround for standalone backslash | 644 # Workaround for standalone backslash |
| 645 |
620 def u(s): | 646 def u(s): |
621 return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") | 647 return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") |
622 unichr = unichr | 648 unichr = unichr |
623 int2byte = chr | 649 int2byte = chr |
| 650 |
624 def byte2int(bs): | 651 def byte2int(bs): |
625 return ord(bs[0]) | 652 return ord(bs[0]) |
| 653 |
626 def indexbytes(buf, i): | 654 def indexbytes(buf, i): |
627 return ord(buf[i]) | 655 return ord(buf[i]) |
628 iterbytes = functools.partial(itertools.imap, ord) | 656 iterbytes = functools.partial(itertools.imap, ord) |
629 import StringIO | 657 import StringIO |
630 StringIO = BytesIO = StringIO.StringIO | 658 StringIO = BytesIO = StringIO.StringIO |
631 _assertCountEqual = "assertItemsEqual" | 659 _assertCountEqual = "assertItemsEqual" |
632 _assertRaisesRegex = "assertRaisesRegexp" | 660 _assertRaisesRegex = "assertRaisesRegexp" |
633 _assertRegex = "assertRegexpMatches" | 661 _assertRegex = "assertRegexpMatches" |
634 _add_doc(b, """Byte literal""") | 662 _add_doc(b, """Byte literal""") |
635 _add_doc(u, """Text literal""") | 663 _add_doc(u, """Text literal""") |
636 | 664 |
637 | 665 |
638 def assertCountEqual(self, *args, **kwargs): | 666 def assertCountEqual(self, *args, **kwargs): |
639 return getattr(self, _assertCountEqual)(*args, **kwargs) | 667 return getattr(self, _assertCountEqual)(*args, **kwargs) |
640 | 668 |
641 | 669 |
642 def assertRaisesRegex(self, *args, **kwargs): | 670 def assertRaisesRegex(self, *args, **kwargs): |
643 return getattr(self, _assertRaisesRegex)(*args, **kwargs) | 671 return getattr(self, _assertRaisesRegex)(*args, **kwargs) |
644 | 672 |
645 | 673 |
646 def assertRegex(self, *args, **kwargs): | 674 def assertRegex(self, *args, **kwargs): |
647 return getattr(self, _assertRegex)(*args, **kwargs) | 675 return getattr(self, _assertRegex)(*args, **kwargs) |
648 | 676 |
649 | 677 |
650 if PY3: | 678 if PY3: |
651 exec_ = getattr(moves.builtins, "exec") | 679 exec_ = getattr(moves.builtins, "exec") |
652 | 680 |
653 | |
654 def reraise(tp, value, tb=None): | 681 def reraise(tp, value, tb=None): |
655 if value is None: | 682 if value is None: |
656 value = tp() | 683 value = tp() |
657 if value.__traceback__ is not tb: | 684 if value.__traceback__ is not tb: |
658 raise value.with_traceback(tb) | 685 raise value.with_traceback(tb) |
659 raise value | 686 raise value |
660 | 687 |
661 else: | 688 else: |
662 def exec_(_code_, _globs_=None, _locs_=None): | 689 def exec_(_code_, _globs_=None, _locs_=None): |
663 """Execute code in a namespace.""" | 690 """Execute code in a namespace.""" |
664 if _globs_ is None: | 691 if _globs_ is None: |
665 frame = sys._getframe(1) | 692 frame = sys._getframe(1) |
666 _globs_ = frame.f_globals | 693 _globs_ = frame.f_globals |
667 if _locs_ is None: | 694 if _locs_ is None: |
668 _locs_ = frame.f_locals | 695 _locs_ = frame.f_locals |
669 del frame | 696 del frame |
670 elif _locs_ is None: | 697 elif _locs_ is None: |
671 _locs_ = _globs_ | 698 _locs_ = _globs_ |
672 exec("""exec _code_ in _globs_, _locs_""") | 699 exec("""exec _code_ in _globs_, _locs_""") |
673 | 700 |
674 | |
675 exec_("""def reraise(tp, value, tb=None): | 701 exec_("""def reraise(tp, value, tb=None): |
676 raise tp, value, tb | 702 raise tp, value, tb |
677 """) | 703 """) |
678 | 704 |
679 | 705 |
680 if sys.version_info[:2] == (3, 2): | 706 if sys.version_info[:2] == (3, 2): |
681 exec_("""def raise_from(value, from_value): | 707 exec_("""def raise_from(value, from_value): |
682 if from_value is None: | 708 if from_value is None: |
683 raise value | 709 raise value |
684 raise value from from_value | 710 raise value from from_value |
685 """) | 711 """) |
686 elif sys.version_info[:2] > (3, 2): | 712 elif sys.version_info[:2] > (3, 2): |
687 exec_("""def raise_from(value, from_value): | 713 exec_("""def raise_from(value, from_value): |
688 raise value from from_value | 714 raise value from from_value |
689 """) | 715 """) |
690 else: | 716 else: |
691 def raise_from(value, from_value): | 717 def raise_from(value, from_value): |
692 raise value | 718 raise value |
693 | 719 |
694 | 720 |
695 print_ = getattr(moves.builtins, "print", None) | 721 print_ = getattr(moves.builtins, "print", None) |
696 if print_ is None: | 722 if print_ is None: |
697 def print_(*args, **kwargs): | 723 def print_(*args, **kwargs): |
698 """The new-style print function for Python 2.4 and 2.5.""" | 724 """The new-style print function for Python 2.4 and 2.5.""" |
699 fp = kwargs.pop("file", sys.stdout) | 725 fp = kwargs.pop("file", sys.stdout) |
700 if fp is None: | 726 if fp is None: |
701 return | 727 return |
| 728 |
702 def write(data): | 729 def write(data): |
703 if not isinstance(data, basestring): | 730 if not isinstance(data, basestring): |
704 data = str(data) | 731 data = str(data) |
705 # If the file has an encoding, encode unicode with it. | 732 # If the file has an encoding, encode unicode with it. |
706 if (isinstance(fp, file) and | 733 if (isinstance(fp, file) and |
707 isinstance(data, unicode) and | 734 isinstance(data, unicode) and |
708 fp.encoding is not None): | 735 fp.encoding is not None): |
709 errors = getattr(fp, "errors", None) | 736 errors = getattr(fp, "errors", None) |
710 if errors is None: | 737 if errors is None: |
711 errors = "strict" | 738 errors = "strict" |
712 data = data.encode(fp.encoding, errors) | 739 data = data.encode(fp.encoding, errors) |
713 fp.write(data) | 740 fp.write(data) |
714 want_unicode = False | 741 want_unicode = False |
715 sep = kwargs.pop("sep", None) | 742 sep = kwargs.pop("sep", None) |
716 if sep is not None: | 743 if sep is not None: |
717 if isinstance(sep, unicode): | 744 if isinstance(sep, unicode): |
718 want_unicode = True | 745 want_unicode = True |
(...skipping 22 matching lines...) Expand all Loading... |
741 sep = space | 768 sep = space |
742 if end is None: | 769 if end is None: |
743 end = newline | 770 end = newline |
744 for i, arg in enumerate(args): | 771 for i, arg in enumerate(args): |
745 if i: | 772 if i: |
746 write(sep) | 773 write(sep) |
747 write(arg) | 774 write(arg) |
748 write(end) | 775 write(end) |
749 if sys.version_info[:2] < (3, 3): | 776 if sys.version_info[:2] < (3, 3): |
750 _print = print_ | 777 _print = print_ |
| 778 |
751 def print_(*args, **kwargs): | 779 def print_(*args, **kwargs): |
752 fp = kwargs.get("file", sys.stdout) | 780 fp = kwargs.get("file", sys.stdout) |
753 flush = kwargs.pop("flush", False) | 781 flush = kwargs.pop("flush", False) |
754 _print(*args, **kwargs) | 782 _print(*args, **kwargs) |
755 if flush and fp is not None: | 783 if flush and fp is not None: |
756 fp.flush() | 784 fp.flush() |
757 | 785 |
758 _add_doc(reraise, """Reraise an exception.""") | 786 _add_doc(reraise, """Reraise an exception.""") |
759 | 787 |
760 if sys.version_info[0:2] < (3, 4): | 788 if sys.version_info[0:2] < (3, 4): |
761 def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, | 789 def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, |
762 updated=functools.WRAPPER_UPDATES): | 790 updated=functools.WRAPPER_UPDATES): |
763 def wrapper(f): | 791 def wrapper(f): |
764 f = functools.wraps(wrapped, assigned, updated)(f) | 792 f = functools.wraps(wrapped, assigned, updated)(f) |
765 f.__wrapped__ = wrapped | 793 f.__wrapped__ = wrapped |
766 return f | 794 return f |
767 return wrapper | 795 return wrapper |
768 else: | 796 else: |
769 wraps = functools.wraps | 797 wraps = functools.wraps |
770 | 798 |
| 799 |
771 def with_metaclass(meta, *bases): | 800 def with_metaclass(meta, *bases): |
772 """Create a base class with a metaclass.""" | 801 """Create a base class with a metaclass.""" |
773 # This requires a bit of explanation: the basic idea is to make a dummy | 802 # This requires a bit of explanation: the basic idea is to make a dummy |
774 # metaclass for one level of class instantiation that replaces itself with | 803 # metaclass for one level of class instantiation that replaces itself with |
775 # the actual metaclass. | 804 # the actual metaclass. |
776 class metaclass(meta): | 805 class metaclass(meta): |
| 806 |
777 def __new__(cls, name, this_bases, d): | 807 def __new__(cls, name, this_bases, d): |
778 return meta(name, bases, d) | 808 return meta(name, bases, d) |
779 return type.__new__(metaclass, 'temporary_class', (), {}) | 809 return type.__new__(metaclass, 'temporary_class', (), {}) |
780 | 810 |
781 | 811 |
782 def add_metaclass(metaclass): | 812 def add_metaclass(metaclass): |
783 """Class decorator for creating a class with a metaclass.""" | 813 """Class decorator for creating a class with a metaclass.""" |
784 def wrapper(cls): | 814 def wrapper(cls): |
785 orig_vars = cls.__dict__.copy() | 815 orig_vars = cls.__dict__.copy() |
786 slots = orig_vars.get('__slots__') | 816 slots = orig_vars.get('__slots__') |
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
823 # Remove other six meta path importers, since they cause problems. This can | 853 # Remove other six meta path importers, since they cause problems. This can |
824 # happen if six is removed from sys.modules and then reloaded. (Setuptools does | 854 # happen if six is removed from sys.modules and then reloaded. (Setuptools does |
825 # this for some reason.) | 855 # this for some reason.) |
826 if sys.meta_path: | 856 if sys.meta_path: |
827 for i, importer in enumerate(sys.meta_path): | 857 for i, importer in enumerate(sys.meta_path): |
828 # Here's some real nastiness: Another "instance" of the six module might | 858 # Here's some real nastiness: Another "instance" of the six module might |
829 # be floating around. Therefore, we can't use isinstance() to check for | 859 # be floating around. Therefore, we can't use isinstance() to check for |
830 # the six meta path importer, since the other six instance will have | 860 # the six meta path importer, since the other six instance will have |
831 # inserted an importer with different class. | 861 # inserted an importer with different class. |
832 if (type(importer).__name__ == "_SixMetaPathImporter" and | 862 if (type(importer).__name__ == "_SixMetaPathImporter" and |
833 importer.name == __name__): | 863 importer.name == __name__): |
834 del sys.meta_path[i] | 864 del sys.meta_path[i] |
835 break | 865 break |
836 del i, importer | 866 del i, importer |
837 # Finally, add the importer to the meta path import hook. | 867 # Finally, add the importer to the meta path import hook. |
838 sys.meta_path.append(_importer) | 868 sys.meta_path.append(_importer) |
OLD | NEW |