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