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