1"""Utilities for writing code that runs on Python 2 and 3""" 2 3# Copyright (c) 2010-2014 Benjamin Peterson 4# 5# 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 7# in the Software without restriction, including without limitation the rights 8# 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 10# furnished to do so, subject to the following conditions: 11# 12# The above copyright notice and this permission notice shall be included in all 13# copies or substantial portions of the Software. 14# 15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17# 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 19# 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 21# SOFTWARE. 22 23from __future__ import absolute_import 24 25import functools 26import itertools 27import operator 28import sys 29import types 30 31__author__ = "Benjamin Peterson <benjamin@python.org>" 32__version__ = "1.8.0" 33 34 35# Useful for very coarse version differentiation. 36PY2 = sys.version_info[0] == 2 37PY3 = sys.version_info[0] == 3 38 39if PY3: 40 string_types = str, 41 integer_types = int, 42 class_types = type, 43 text_type = str 44 binary_type = bytes 45 46 MAXSIZE = sys.maxsize 47else: 48 string_types = basestring, 49 integer_types = (int, long) 50 class_types = (type, types.ClassType) 51 text_type = unicode 52 binary_type = str 53 54 if sys.platform.startswith("java"): 55 # Jython always uses 32 bits. 56 MAXSIZE = int((1 << 31) - 1) 57 else: 58 # It's possible to have sizeof(long) != sizeof(Py_ssize_t). 59 class X(object): 60 def __len__(self): 61 return 1 << 31 62 try: 63 len(X()) 64 except OverflowError: 65 # 32-bit 66 MAXSIZE = int((1 << 31) - 1) 67 else: 68 # 64-bit 69 MAXSIZE = int((1 << 63) - 1) 70 del X 71 72 73def _add_doc(func, doc): 74 """Add documentation to a function.""" 75 func.__doc__ = doc 76 77 78def _import_module(name): 79 """Import module, returning the module after the last dot.""" 80 __import__(name) 81 return sys.modules[name] 82 83 84class _LazyDescr(object): 85 86 def __init__(self, name): 87 self.name = name 88 89 def __get__(self, obj, tp): 90 result = self._resolve() 91 setattr(obj, self.name, result) # Invokes __set__. 92 try: 93 # This is a bit ugly, but it avoids running this again by 94 # removing this descriptor. 95 delattr(obj.__class__, self.name) 96 except AttributeError: 97 pass 98 return result 99 100 101class MovedModule(_LazyDescr): 102 103 def __init__(self, name, old, new=None): 104 super(MovedModule, self).__init__(name) 105 if PY3: 106 if new is None: 107 new = name 108 self.mod = new 109 else: 110 self.mod = old 111 112 def _resolve(self): 113 return _import_module(self.mod) 114 115 def __getattr__(self, attr): 116 _module = self._resolve() 117 value = getattr(_module, attr) 118 setattr(self, attr, value) 119 return value 120 121 122class _LazyModule(types.ModuleType): 123 124 def __init__(self, name): 125 super(_LazyModule, self).__init__(name) 126 self.__doc__ = self.__class__.__doc__ 127 128 def __dir__(self): 129 attrs = ["__doc__", "__name__"] 130 attrs += [attr.name for attr in self._moved_attributes] 131 return attrs 132 133 # Subclasses should override this 134 _moved_attributes = [] 135 136 137class MovedAttribute(_LazyDescr): 138 139 def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): 140 super(MovedAttribute, self).__init__(name) 141 if PY3: 142 if new_mod is None: 143 new_mod = name 144 self.mod = new_mod 145 if new_attr is None: 146 if old_attr is None: 147 new_attr = name 148 else: 149 new_attr = old_attr 150 self.attr = new_attr 151 else: 152 self.mod = old_mod 153 if old_attr is None: 154 old_attr = name 155 self.attr = old_attr 156 157 def _resolve(self): 158 module = _import_module(self.mod) 159 return getattr(module, self.attr) 160 161 162class _SixMetaPathImporter(object): 163 """ 164 A meta path importer to import six.moves and its submodules. 165 166 This class implements a PEP302 finder and loader. It should be compatible 167 with Python 2.5 and all existing versions of Python3 168 """ 169 def __init__(self, six_module_name): 170 self.name = six_module_name 171 self.known_modules = {} 172 173 def _add_module(self, mod, *fullnames): 174 for fullname in fullnames: 175 self.known_modules[self.name + "." + fullname] = mod 176 177 def _get_module(self, fullname): 178 return self.known_modules[self.name + "." + fullname] 179 180 def find_module(self, fullname, path=None): 181 if fullname in self.known_modules: 182 return self 183 return None 184 185 def __get_module(self, fullname): 186 try: 187 return self.known_modules[fullname] 188 except KeyError: 189 raise ImportError("This loader does not know module " + fullname) 190 191 def load_module(self, fullname): 192 try: 193 # in case of a reload 194 return sys.modules[fullname] 195 except KeyError: 196 pass 197 mod = self.__get_module(fullname) 198 if isinstance(mod, MovedModule): 199 mod = mod._resolve() 200 else: 201 mod.__loader__ = self 202 sys.modules[fullname] = mod 203 return mod 204 205 def is_package(self, fullname): 206 """ 207 Return true, if the named module is a package. 208 209 We need this method to get correct spec objects with 210 Python 3.4 (see PEP451) 211 """ 212 return hasattr(self.__get_module(fullname), "__path__") 213 214 def get_code(self, fullname): 215 """Return None 216 217 Required, if is_package is implemented""" 218 self.__get_module(fullname) # eventually raises ImportError 219 return None 220 get_source = get_code # same as get_code 221 222_importer = _SixMetaPathImporter(__name__) 223 224 225class _MovedItems(_LazyModule): 226 """Lazy loading of moved objects""" 227 __path__ = [] # mark as package 228 229 230_moved_attributes = [ 231 MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), 232 MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), 233 MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), 234 MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), 235 MovedAttribute("intern", "__builtin__", "sys"), 236 MovedAttribute("map", "itertools", "builtins", "imap", "map"), 237 MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), 238 MovedAttribute("reload_module", "__builtin__", "imp", "reload"), 239 MovedAttribute("reduce", "__builtin__", "functools"), 240 MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), 241 MovedAttribute("StringIO", "StringIO", "io"), 242 MovedAttribute("UserDict", "UserDict", "collections"), 243 MovedAttribute("UserList", "UserList", "collections"), 244 MovedAttribute("UserString", "UserString", "collections"), 245 MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), 246 MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), 247 MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), 248 249 MovedModule("builtins", "__builtin__"), 250 MovedModule("configparser", "ConfigParser"), 251 MovedModule("copyreg", "copy_reg"), 252 MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), 253 MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), 254 MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), 255 MovedModule("http_cookies", "Cookie", "http.cookies"), 256 MovedModule("html_entities", "htmlentitydefs", "html.entities"), 257 MovedModule("html_parser", "HTMLParser", "html.parser"), 258 MovedModule("http_client", "httplib", "http.client"), 259 MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), 260 MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), 261 MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), 262 MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), 263 MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), 264 MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), 265 MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), 266 MovedModule("cPickle", "cPickle", "pickle"), 267 MovedModule("queue", "Queue"), 268 MovedModule("reprlib", "repr"), 269 MovedModule("socketserver", "SocketServer"), 270 MovedModule("_thread", "thread", "_thread"), 271 MovedModule("tkinter", "Tkinter"), 272 MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), 273 MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), 274 MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), 275 MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), 276 MovedModule("tkinter_tix", "Tix", "tkinter.tix"), 277 MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), 278 MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), 279 MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), 280 MovedModule("tkinter_colorchooser", "tkColorChooser", 281 "tkinter.colorchooser"), 282 MovedModule("tkinter_commondialog", "tkCommonDialog", 283 "tkinter.commondialog"), 284 MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), 285 MovedModule("tkinter_font", "tkFont", "tkinter.font"), 286 MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), 287 MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", 288 "tkinter.simpledialog"), 289 MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), 290 MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), 291 MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), 292 MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), 293 MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), 294 MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), 295 MovedModule("winreg", "_winreg"), 296] 297for attr in _moved_attributes: 298 setattr(_MovedItems, attr.name, attr) 299 if isinstance(attr, MovedModule): 300 _importer._add_module(attr, "moves." + attr.name) 301del attr 302 303_MovedItems._moved_attributes = _moved_attributes 304 305moves = _MovedItems(__name__ + ".moves") 306_importer._add_module(moves, "moves") 307 308 309class Module_six_moves_urllib_parse(_LazyModule): 310 """Lazy loading of moved objects in six.moves.urllib_parse""" 311 312 313_urllib_parse_moved_attributes = [ 314 MovedAttribute("ParseResult", "urlparse", "urllib.parse"), 315 MovedAttribute("SplitResult", "urlparse", "urllib.parse"), 316 MovedAttribute("parse_qs", "urlparse", "urllib.parse"), 317 MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), 318 MovedAttribute("urldefrag", "urlparse", "urllib.parse"), 319 MovedAttribute("urljoin", "urlparse", "urllib.parse"), 320 MovedAttribute("urlparse", "urlparse", "urllib.parse"), 321 MovedAttribute("urlsplit", "urlparse", "urllib.parse"), 322 MovedAttribute("urlunparse", "urlparse", "urllib.parse"), 323 MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), 324 MovedAttribute("quote", "urllib", "urllib.parse"), 325 MovedAttribute("quote_plus", "urllib", "urllib.parse"), 326 MovedAttribute("unquote", "urllib", "urllib.parse"), 327 MovedAttribute("unquote_plus", "urllib", "urllib.parse"), 328 MovedAttribute("urlencode", "urllib", "urllib.parse"), 329 MovedAttribute("splitquery", "urllib", "urllib.parse"), 330 MovedAttribute("splittag", "urllib", "urllib.parse"), 331 MovedAttribute("splituser", "urllib", "urllib.parse"), 332 MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), 333 MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), 334 MovedAttribute("uses_params", "urlparse", "urllib.parse"), 335 MovedAttribute("uses_query", "urlparse", "urllib.parse"), 336 MovedAttribute("uses_relative", "urlparse", "urllib.parse"), 337] 338for attr in _urllib_parse_moved_attributes: 339 setattr(Module_six_moves_urllib_parse, attr.name, attr) 340del attr 341 342Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes 343 344_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), 345 "moves.urllib_parse", "moves.urllib.parse") 346 347 348class Module_six_moves_urllib_error(_LazyModule): 349 """Lazy loading of moved objects in six.moves.urllib_error""" 350 351 352_urllib_error_moved_attributes = [ 353 MovedAttribute("URLError", "urllib2", "urllib.error"), 354 MovedAttribute("HTTPError", "urllib2", "urllib.error"), 355 MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), 356] 357for attr in _urllib_error_moved_attributes: 358 setattr(Module_six_moves_urllib_error, attr.name, attr) 359del attr 360 361Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes 362 363_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), 364 "moves.urllib_error", "moves.urllib.error") 365 366 367class Module_six_moves_urllib_request(_LazyModule): 368 """Lazy loading of moved objects in six.moves.urllib_request""" 369 370 371_urllib_request_moved_attributes = [ 372 MovedAttribute("urlopen", "urllib2", "urllib.request"), 373 MovedAttribute("install_opener", "urllib2", "urllib.request"), 374 MovedAttribute("build_opener", "urllib2", "urllib.request"), 375 MovedAttribute("pathname2url", "urllib", "urllib.request"), 376 MovedAttribute("url2pathname", "urllib", "urllib.request"), 377 MovedAttribute("getproxies", "urllib", "urllib.request"), 378 MovedAttribute("Request", "urllib2", "urllib.request"), 379 MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), 380 MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), 381 MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), 382 MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), 383 MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), 384 MovedAttribute("BaseHandler", "urllib2", "urllib.request"), 385 MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), 386 MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), 387 MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), 388 MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), 389 MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), 390 MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), 391 MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), 392 MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), 393 MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), 394 MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), 395 MovedAttribute("FileHandler", "urllib2", "urllib.request"), 396 MovedAttribute("FTPHandler", "urllib2", "urllib.request"), 397 MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), 398 MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), 399 MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), 400 MovedAttribute("urlretrieve", "urllib", "urllib.request"), 401 MovedAttribute("urlcleanup", "urllib", "urllib.request"), 402 MovedAttribute("URLopener", "urllib", "urllib.request"), 403 MovedAttribute("FancyURLopener", "urllib", "urllib.request"), 404 MovedAttribute("proxy_bypass", "urllib", "urllib.request"), 405] 406for attr in _urllib_request_moved_attributes: 407 setattr(Module_six_moves_urllib_request, attr.name, attr) 408del attr 409 410Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes 411 412_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), 413 "moves.urllib_request", "moves.urllib.request") 414 415 416class Module_six_moves_urllib_response(_LazyModule): 417 """Lazy loading of moved objects in six.moves.urllib_response""" 418 419 420_urllib_response_moved_attributes = [ 421 MovedAttribute("addbase", "urllib", "urllib.response"), 422 MovedAttribute("addclosehook", "urllib", "urllib.response"), 423 MovedAttribute("addinfo", "urllib", "urllib.response"), 424 MovedAttribute("addinfourl", "urllib", "urllib.response"), 425] 426for attr in _urllib_response_moved_attributes: 427 setattr(Module_six_moves_urllib_response, attr.name, attr) 428del attr 429 430Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes 431 432_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), 433 "moves.urllib_response", "moves.urllib.response") 434 435 436class Module_six_moves_urllib_robotparser(_LazyModule): 437 """Lazy loading of moved objects in six.moves.urllib_robotparser""" 438 439 440_urllib_robotparser_moved_attributes = [ 441 MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), 442] 443for attr in _urllib_robotparser_moved_attributes: 444 setattr(Module_six_moves_urllib_robotparser, attr.name, attr) 445del attr 446 447Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes 448 449_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), 450 "moves.urllib_robotparser", "moves.urllib.robotparser") 451 452 453class Module_six_moves_urllib(types.ModuleType): 454 """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" 455 __path__ = [] # mark as package 456 parse = _importer._get_module("moves.urllib_parse") 457 error = _importer._get_module("moves.urllib_error") 458 request = _importer._get_module("moves.urllib_request") 459 response = _importer._get_module("moves.urllib_response") 460 robotparser = _importer._get_module("moves.urllib_robotparser") 461 462 def __dir__(self): 463 return ['parse', 'error', 'request', 'response', 'robotparser'] 464 465_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), 466 "moves.urllib") 467 468 469def add_move(move): 470 """Add an item to six.moves.""" 471 setattr(_MovedItems, move.name, move) 472 473 474def remove_move(name): 475 """Remove item from six.moves.""" 476 try: 477 delattr(_MovedItems, name) 478 except AttributeError: 479 try: 480 del moves.__dict__[name] 481 except KeyError: 482 raise AttributeError("no such move, %r" % (name,)) 483 484 485if PY3: 486 _meth_func = "__func__" 487 _meth_self = "__self__" 488 489 _func_closure = "__closure__" 490 _func_code = "__code__" 491 _func_defaults = "__defaults__" 492 _func_globals = "__globals__" 493else: 494 _meth_func = "im_func" 495 _meth_self = "im_self" 496 497 _func_closure = "func_closure" 498 _func_code = "func_code" 499 _func_defaults = "func_defaults" 500 _func_globals = "func_globals" 501 502 503try: 504 advance_iterator = next 505except NameError: 506 def advance_iterator(it): 507 return it.next() 508next = advance_iterator 509 510 511try: 512 callable = callable 513except NameError: 514 def callable(obj): 515 return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) 516 517 518if PY3: 519 def get_unbound_function(unbound): 520 return unbound 521 522 create_bound_method = types.MethodType 523 524 Iterator = object 525else: 526 def get_unbound_function(unbound): 527 return unbound.im_func 528 529 def create_bound_method(func, obj): 530 return types.MethodType(func, obj, obj.__class__) 531 532 class Iterator(object): 533 534 def next(self): 535 return type(self).__next__(self) 536 537 callable = callable 538_add_doc(get_unbound_function, 539 """Get the function out of a possibly unbound function""") 540 541 542get_method_function = operator.attrgetter(_meth_func) 543get_method_self = operator.attrgetter(_meth_self) 544get_function_closure = operator.attrgetter(_func_closure) 545get_function_code = operator.attrgetter(_func_code) 546get_function_defaults = operator.attrgetter(_func_defaults) 547get_function_globals = operator.attrgetter(_func_globals) 548 549 550if PY3: 551 def iterkeys(d, **kw): 552 return iter(d.keys(**kw)) 553 554 def itervalues(d, **kw): 555 return iter(d.values(**kw)) 556 557 def iteritems(d, **kw): 558 return iter(d.items(**kw)) 559 560 def iterlists(d, **kw): 561 return iter(d.lists(**kw)) 562 563 viewkeys = operator.methodcaller("keys") 564 565 viewvalues = operator.methodcaller("values") 566 567 viewitems = operator.methodcaller("items") 568else: 569 def iterkeys(d, **kw): 570 return iter(d.iterkeys(**kw)) 571 572 def itervalues(d, **kw): 573 return iter(d.itervalues(**kw)) 574 575 def iteritems(d, **kw): 576 return iter(d.iteritems(**kw)) 577 578 def iterlists(d, **kw): 579 return iter(d.iterlists(**kw)) 580 581 viewkeys = operator.methodcaller("viewkeys") 582 583 viewvalues = operator.methodcaller("viewvalues") 584 585 viewitems = operator.methodcaller("viewitems") 586 587_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.") 589_add_doc(iteritems, 590 "Return an iterator over the (key, value) pairs of a dictionary.") 591_add_doc(iterlists, 592 "Return an iterator over the (key, [values]) pairs of a dictionary.") 593 594 595if PY3: 596 def b(s): 597 return s.encode("latin-1") 598 def u(s): 599 return s 600 unichr = chr 601 if sys.version_info[1] <= 1: 602 def int2byte(i): 603 return bytes((i,)) 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) 608 indexbytes = operator.getitem 609 iterbytes = iter 610 import io 611 StringIO = io.StringIO 612 BytesIO = io.BytesIO 613else: 614 def b(s): 615 return s 616 # Workaround for standalone backslash 617 def u(s): 618 return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") 619 unichr = unichr 620 int2byte = chr 621 def byte2int(bs): 622 return ord(bs[0]) 623 def indexbytes(buf, i): 624 return ord(buf[i]) 625 iterbytes = functools.partial(itertools.imap, ord) 626 import StringIO 627 StringIO = BytesIO = StringIO.StringIO 628_add_doc(b, """Byte literal""") 629_add_doc(u, """Text literal""") 630 631 632if PY3: 633 exec_ = getattr(moves.builtins, "exec") 634 635 636 def reraise(tp, value, tb=None): 637 if value is None: 638 value = tp() 639 if value.__traceback__ is not tb: 640 raise value.with_traceback(tb) 641 raise value 642 643else: 644 def exec_(_code_, _globs_=None, _locs_=None): 645 """Execute code in a namespace.""" 646 if _globs_ is None: 647 frame = sys._getframe(1) 648 _globs_ = frame.f_globals 649 if _locs_ is None: 650 _locs_ = frame.f_locals 651 del frame 652 elif _locs_ is None: 653 _locs_ = _globs_ 654 exec("""exec _code_ in _globs_, _locs_""") 655 656 657 exec_("""def reraise(tp, value, tb=None): 658 raise tp, value, tb 659""") 660 661 662if sys.version_info > (3, 2): 663 exec_("""def raise_from(value, from_value): 664 raise value from from_value 665""") 666else: 667 def raise_from(value, from_value): 668 raise value 669 670 671print_ = getattr(moves.builtins, "print", None) 672if print_ is None: 673 def print_(*args, **kwargs): 674 """The new-style print function for Python 2.4 and 2.5.""" 675 fp = kwargs.pop("file", sys.stdout) 676 if fp is None: 677 return 678 def write(data): 679 if not isinstance(data, basestring): 680 data = str(data) 681 # If the file has an encoding, encode unicode with it. 682 if (isinstance(fp, file) and 683 isinstance(data, unicode) and 684 fp.encoding is not None): 685 errors = getattr(fp, "errors", None) 686 if errors is None: 687 errors = "strict" 688 data = data.encode(fp.encoding, errors) 689 fp.write(data) 690 want_unicode = False 691 sep = kwargs.pop("sep", None) 692 if sep is not None: 693 if isinstance(sep, unicode): 694 want_unicode = True 695 elif not isinstance(sep, str): 696 raise TypeError("sep must be None or a string") 697 end = kwargs.pop("end", None) 698 if end is not None: 699 if isinstance(end, unicode): 700 want_unicode = True 701 elif not isinstance(end, str): 702 raise TypeError("end must be None or a string") 703 if kwargs: 704 raise TypeError("invalid keyword arguments to print()") 705 if not want_unicode: 706 for arg in args: 707 if isinstance(arg, unicode): 708 want_unicode = True 709 break 710 if want_unicode: 711 newline = unicode("\n") 712 space = unicode(" ") 713 else: 714 newline = "\n" 715 space = " " 716 if sep is None: 717 sep = space 718 if end is None: 719 end = newline 720 for i, arg in enumerate(args): 721 if i: 722 write(sep) 723 write(arg) 724 write(end) 725 726_add_doc(reraise, """Reraise an exception.""") 727 728if sys.version_info[0:2] < (3, 4): 729 def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, 730 updated=functools.WRAPPER_UPDATES): 731 def wrapper(f): 732 f = functools.wraps(wrapped, assigned, updated)(f) 733 f.__wrapped__ = wrapped 734 return f 735 return wrapper 736else: 737 wraps = functools.wraps 738 739def with_metaclass(meta, *bases): 740 """Create a base class with a metaclass.""" 741 # This requires a bit of explanation: the basic idea is to make a dummy 742 # metaclass for one level of class instantiation that replaces itself with 743 # the actual metaclass. 744 class metaclass(meta): 745 def __new__(cls, name, this_bases, d): 746 return meta(name, bases, d) 747 return type.__new__(metaclass, 'temporary_class', (), {}) 748 749 750def add_metaclass(metaclass): 751 """Class decorator for creating a class with a metaclass.""" 752 def wrapper(cls): 753 orig_vars = cls.__dict__.copy() 754 slots = orig_vars.get('__slots__') 755 if slots is not None: 756 if isinstance(slots, str): 757 slots = [slots] 758 for slots_var in slots: 759 orig_vars.pop(slots_var) 760 orig_vars.pop('__dict__', None) 761 orig_vars.pop('__weakref__', None) 762 return metaclass(cls.__name__, cls.__bases__, orig_vars) 763 return wrapper 764 765# Complete the moves implementation. 766# This code is at the end of this module to speed up module loading. 767# Turn this module into a package. 768__path__ = [] # required for PEP 302 and PEP 451 769__package__ = __name__ # see PEP 366 @ReservedAssignment 770if globals().get("__spec__") is not None: 771 __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable 772# Remove other six meta path importers, since they cause problems. This can 773# happen if six is removed from sys.modules and then reloaded. (Setuptools does 774# this for some reason.) 775if sys.meta_path: 776 for i, importer in enumerate(sys.meta_path): 777 # Here's some real nastiness: Another "instance" of the six module might 778 # be floating around. Therefore, we can't use isinstance() to check for 779 # the six meta path importer, since the other six instance will have 780 # inserted an importer with different class. 781 if (type(importer).__name__ == "_SixMetaPathImporter" and 782 importer.name == __name__): 783 del sys.meta_path[i] 784 break 785 del i, importer 786# Finally, add the importer to the meta path import hook. 787sys.meta_path.append(_importer) 788