Path: blob/master/venv/Lib/site-packages/urllib3/packages/six.py
811 views
# Copyright (c) 2010-2019 Benjamin Peterson1#2# Permission is hereby granted, free of charge, to any person obtaining a copy3# of this software and associated documentation files (the "Software"), to deal4# in the Software without restriction, including without limitation the rights5# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell6# copies of the Software, and to permit persons to whom the Software is7# furnished to do so, subject to the following conditions:8#9# The above copyright notice and this permission notice shall be included in all10# copies or substantial portions of the Software.11#12# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR13# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,14# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE15# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER16# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,17# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE18# SOFTWARE.1920"""Utilities for writing code that runs on Python 2 and 3"""2122from __future__ import absolute_import2324import functools25import itertools26import operator27import sys28import types2930__author__ = "Benjamin Peterson <[email protected]>"31__version__ = "1.12.0"323334# Useful for very coarse version differentiation.35PY2 = sys.version_info[0] == 236PY3 = sys.version_info[0] == 337PY34 = sys.version_info[0:2] >= (3, 4)3839if PY3:40string_types = (str,)41integer_types = (int,)42class_types = (type,)43text_type = str44binary_type = bytes4546MAXSIZE = sys.maxsize47else:48string_types = (basestring,)49integer_types = (int, long)50class_types = (type, types.ClassType)51text_type = unicode52binary_type = str5354if sys.platform.startswith("java"):55# Jython always uses 32 bits.56MAXSIZE = int((1 << 31) - 1)57else:58# It's possible to have sizeof(long) != sizeof(Py_ssize_t).59class X(object):60def __len__(self):61return 1 << 316263try:64len(X())65except OverflowError:66# 32-bit67MAXSIZE = int((1 << 31) - 1)68else:69# 64-bit70MAXSIZE = int((1 << 63) - 1)71del X727374def _add_doc(func, doc):75"""Add documentation to a function."""76func.__doc__ = doc777879def _import_module(name):80"""Import module, returning the module after the last dot."""81__import__(name)82return sys.modules[name]838485class _LazyDescr(object):86def __init__(self, name):87self.name = name8889def __get__(self, obj, tp):90result = self._resolve()91setattr(obj, self.name, result) # Invokes __set__.92try:93# This is a bit ugly, but it avoids running this again by94# removing this descriptor.95delattr(obj.__class__, self.name)96except AttributeError:97pass98return result99100101class MovedModule(_LazyDescr):102def __init__(self, name, old, new=None):103super(MovedModule, self).__init__(name)104if PY3:105if new is None:106new = name107self.mod = new108else:109self.mod = old110111def _resolve(self):112return _import_module(self.mod)113114def __getattr__(self, attr):115_module = self._resolve()116value = getattr(_module, attr)117setattr(self, attr, value)118return value119120121class _LazyModule(types.ModuleType):122def __init__(self, name):123super(_LazyModule, self).__init__(name)124self.__doc__ = self.__class__.__doc__125126def __dir__(self):127attrs = ["__doc__", "__name__"]128attrs += [attr.name for attr in self._moved_attributes]129return attrs130131# Subclasses should override this132_moved_attributes = []133134135class MovedAttribute(_LazyDescr):136def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):137super(MovedAttribute, self).__init__(name)138if PY3:139if new_mod is None:140new_mod = name141self.mod = new_mod142if new_attr is None:143if old_attr is None:144new_attr = name145else:146new_attr = old_attr147self.attr = new_attr148else:149self.mod = old_mod150if old_attr is None:151old_attr = name152self.attr = old_attr153154def _resolve(self):155module = _import_module(self.mod)156return getattr(module, self.attr)157158159class _SixMetaPathImporter(object):160161"""162A meta path importer to import six.moves and its submodules.163164This class implements a PEP302 finder and loader. It should be compatible165with Python 2.5 and all existing versions of Python3166"""167168def __init__(self, six_module_name):169self.name = six_module_name170self.known_modules = {}171172def _add_module(self, mod, *fullnames):173for fullname in fullnames:174self.known_modules[self.name + "." + fullname] = mod175176def _get_module(self, fullname):177return self.known_modules[self.name + "." + fullname]178179def find_module(self, fullname, path=None):180if fullname in self.known_modules:181return self182return None183184def __get_module(self, fullname):185try:186return self.known_modules[fullname]187except KeyError:188raise ImportError("This loader does not know module " + fullname)189190def load_module(self, fullname):191try:192# in case of a reload193return sys.modules[fullname]194except KeyError:195pass196mod = self.__get_module(fullname)197if isinstance(mod, MovedModule):198mod = mod._resolve()199else:200mod.__loader__ = self201sys.modules[fullname] = mod202return mod203204def is_package(self, fullname):205"""206Return true, if the named module is a package.207208We need this method to get correct spec objects with209Python 3.4 (see PEP451)210"""211return hasattr(self.__get_module(fullname), "__path__")212213def get_code(self, fullname):214"""Return None215216Required, if is_package is implemented"""217self.__get_module(fullname) # eventually raises ImportError218return None219220get_source = get_code # same as get_code221222223_importer = _SixMetaPathImporter(__name__)224225226class _MovedItems(_LazyModule):227228"""Lazy loading of moved objects"""229230__path__ = [] # mark as package231232233_moved_attributes = [234MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),235MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),236MovedAttribute(237"filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"238),239MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),240MovedAttribute("intern", "__builtin__", "sys"),241MovedAttribute("map", "itertools", "builtins", "imap", "map"),242MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"),243MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"),244MovedAttribute("getoutput", "commands", "subprocess"),245MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),246MovedAttribute(247"reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"248),249MovedAttribute("reduce", "__builtin__", "functools"),250MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),251MovedAttribute("StringIO", "StringIO", "io"),252MovedAttribute("UserDict", "UserDict", "collections"),253MovedAttribute("UserList", "UserList", "collections"),254MovedAttribute("UserString", "UserString", "collections"),255MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),256MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),257MovedAttribute(258"zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"259),260MovedModule("builtins", "__builtin__"),261MovedModule("configparser", "ConfigParser"),262MovedModule("copyreg", "copy_reg"),263MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),264MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"),265MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),266MovedModule("http_cookies", "Cookie", "http.cookies"),267MovedModule("html_entities", "htmlentitydefs", "html.entities"),268MovedModule("html_parser", "HTMLParser", "html.parser"),269MovedModule("http_client", "httplib", "http.client"),270MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),271MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"),272MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),273MovedModule(274"email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"275),276MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),277MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),278MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),279MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),280MovedModule("cPickle", "cPickle", "pickle"),281MovedModule("queue", "Queue"),282MovedModule("reprlib", "repr"),283MovedModule("socketserver", "SocketServer"),284MovedModule("_thread", "thread", "_thread"),285MovedModule("tkinter", "Tkinter"),286MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),287MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),288MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),289MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),290MovedModule("tkinter_tix", "Tix", "tkinter.tix"),291MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),292MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),293MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),294MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"),295MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"),296MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),297MovedModule("tkinter_font", "tkFont", "tkinter.font"),298MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),299MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"),300MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),301MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),302MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),303MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),304MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),305MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),306]307# Add windows specific modules.308if sys.platform == "win32":309_moved_attributes += [MovedModule("winreg", "_winreg")]310311for attr in _moved_attributes:312setattr(_MovedItems, attr.name, attr)313if isinstance(attr, MovedModule):314_importer._add_module(attr, "moves." + attr.name)315del attr316317_MovedItems._moved_attributes = _moved_attributes318319moves = _MovedItems(__name__ + ".moves")320_importer._add_module(moves, "moves")321322323class Module_six_moves_urllib_parse(_LazyModule):324325"""Lazy loading of moved objects in six.moves.urllib_parse"""326327328_urllib_parse_moved_attributes = [329MovedAttribute("ParseResult", "urlparse", "urllib.parse"),330MovedAttribute("SplitResult", "urlparse", "urllib.parse"),331MovedAttribute("parse_qs", "urlparse", "urllib.parse"),332MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),333MovedAttribute("urldefrag", "urlparse", "urllib.parse"),334MovedAttribute("urljoin", "urlparse", "urllib.parse"),335MovedAttribute("urlparse", "urlparse", "urllib.parse"),336MovedAttribute("urlsplit", "urlparse", "urllib.parse"),337MovedAttribute("urlunparse", "urlparse", "urllib.parse"),338MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),339MovedAttribute("quote", "urllib", "urllib.parse"),340MovedAttribute("quote_plus", "urllib", "urllib.parse"),341MovedAttribute("unquote", "urllib", "urllib.parse"),342MovedAttribute("unquote_plus", "urllib", "urllib.parse"),343MovedAttribute(344"unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"345),346MovedAttribute("urlencode", "urllib", "urllib.parse"),347MovedAttribute("splitquery", "urllib", "urllib.parse"),348MovedAttribute("splittag", "urllib", "urllib.parse"),349MovedAttribute("splituser", "urllib", "urllib.parse"),350MovedAttribute("splitvalue", "urllib", "urllib.parse"),351MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),352MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),353MovedAttribute("uses_params", "urlparse", "urllib.parse"),354MovedAttribute("uses_query", "urlparse", "urllib.parse"),355MovedAttribute("uses_relative", "urlparse", "urllib.parse"),356]357for attr in _urllib_parse_moved_attributes:358setattr(Module_six_moves_urllib_parse, attr.name, attr)359del attr360361Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes362363_importer._add_module(364Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),365"moves.urllib_parse",366"moves.urllib.parse",367)368369370class Module_six_moves_urllib_error(_LazyModule):371372"""Lazy loading of moved objects in six.moves.urllib_error"""373374375_urllib_error_moved_attributes = [376MovedAttribute("URLError", "urllib2", "urllib.error"),377MovedAttribute("HTTPError", "urllib2", "urllib.error"),378MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),379]380for attr in _urllib_error_moved_attributes:381setattr(Module_six_moves_urllib_error, attr.name, attr)382del attr383384Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes385386_importer._add_module(387Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),388"moves.urllib_error",389"moves.urllib.error",390)391392393class Module_six_moves_urllib_request(_LazyModule):394395"""Lazy loading of moved objects in six.moves.urllib_request"""396397398_urllib_request_moved_attributes = [399MovedAttribute("urlopen", "urllib2", "urllib.request"),400MovedAttribute("install_opener", "urllib2", "urllib.request"),401MovedAttribute("build_opener", "urllib2", "urllib.request"),402MovedAttribute("pathname2url", "urllib", "urllib.request"),403MovedAttribute("url2pathname", "urllib", "urllib.request"),404MovedAttribute("getproxies", "urllib", "urllib.request"),405MovedAttribute("Request", "urllib2", "urllib.request"),406MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),407MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),408MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),409MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),410MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),411MovedAttribute("BaseHandler", "urllib2", "urllib.request"),412MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),413MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),414MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),415MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),416MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),417MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),418MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),419MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),420MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),421MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),422MovedAttribute("FileHandler", "urllib2", "urllib.request"),423MovedAttribute("FTPHandler", "urllib2", "urllib.request"),424MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),425MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),426MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),427MovedAttribute("urlretrieve", "urllib", "urllib.request"),428MovedAttribute("urlcleanup", "urllib", "urllib.request"),429MovedAttribute("URLopener", "urllib", "urllib.request"),430MovedAttribute("FancyURLopener", "urllib", "urllib.request"),431MovedAttribute("proxy_bypass", "urllib", "urllib.request"),432MovedAttribute("parse_http_list", "urllib2", "urllib.request"),433MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"),434]435for attr in _urllib_request_moved_attributes:436setattr(Module_six_moves_urllib_request, attr.name, attr)437del attr438439Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes440441_importer._add_module(442Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),443"moves.urllib_request",444"moves.urllib.request",445)446447448class Module_six_moves_urllib_response(_LazyModule):449450"""Lazy loading of moved objects in six.moves.urllib_response"""451452453_urllib_response_moved_attributes = [454MovedAttribute("addbase", "urllib", "urllib.response"),455MovedAttribute("addclosehook", "urllib", "urllib.response"),456MovedAttribute("addinfo", "urllib", "urllib.response"),457MovedAttribute("addinfourl", "urllib", "urllib.response"),458]459for attr in _urllib_response_moved_attributes:460setattr(Module_six_moves_urllib_response, attr.name, attr)461del attr462463Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes464465_importer._add_module(466Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),467"moves.urllib_response",468"moves.urllib.response",469)470471472class Module_six_moves_urllib_robotparser(_LazyModule):473474"""Lazy loading of moved objects in six.moves.urllib_robotparser"""475476477_urllib_robotparser_moved_attributes = [478MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser")479]480for attr in _urllib_robotparser_moved_attributes:481setattr(Module_six_moves_urllib_robotparser, attr.name, attr)482del attr483484Module_six_moves_urllib_robotparser._moved_attributes = (485_urllib_robotparser_moved_attributes486)487488_importer._add_module(489Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),490"moves.urllib_robotparser",491"moves.urllib.robotparser",492)493494495class Module_six_moves_urllib(types.ModuleType):496497"""Create a six.moves.urllib namespace that resembles the Python 3 namespace"""498499__path__ = [] # mark as package500parse = _importer._get_module("moves.urllib_parse")501error = _importer._get_module("moves.urllib_error")502request = _importer._get_module("moves.urllib_request")503response = _importer._get_module("moves.urllib_response")504robotparser = _importer._get_module("moves.urllib_robotparser")505506def __dir__(self):507return ["parse", "error", "request", "response", "robotparser"]508509510_importer._add_module(511Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib"512)513514515def add_move(move):516"""Add an item to six.moves."""517setattr(_MovedItems, move.name, move)518519520def remove_move(name):521"""Remove item from six.moves."""522try:523delattr(_MovedItems, name)524except AttributeError:525try:526del moves.__dict__[name]527except KeyError:528raise AttributeError("no such move, %r" % (name,))529530531if PY3:532_meth_func = "__func__"533_meth_self = "__self__"534535_func_closure = "__closure__"536_func_code = "__code__"537_func_defaults = "__defaults__"538_func_globals = "__globals__"539else:540_meth_func = "im_func"541_meth_self = "im_self"542543_func_closure = "func_closure"544_func_code = "func_code"545_func_defaults = "func_defaults"546_func_globals = "func_globals"547548549try:550advance_iterator = next551except NameError:552553def advance_iterator(it):554return it.next()555556557next = advance_iterator558559560try:561callable = callable562except NameError:563564def callable(obj):565return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)566567568if PY3:569570def get_unbound_function(unbound):571return unbound572573create_bound_method = types.MethodType574575def create_unbound_method(func, cls):576return func577578Iterator = object579else:580581def get_unbound_function(unbound):582return unbound.im_func583584def create_bound_method(func, obj):585return types.MethodType(func, obj, obj.__class__)586587def create_unbound_method(func, cls):588return types.MethodType(func, None, cls)589590class Iterator(object):591def next(self):592return type(self).__next__(self)593594callable = callable595_add_doc(596get_unbound_function, """Get the function out of a possibly unbound function"""597)598599600get_method_function = operator.attrgetter(_meth_func)601get_method_self = operator.attrgetter(_meth_self)602get_function_closure = operator.attrgetter(_func_closure)603get_function_code = operator.attrgetter(_func_code)604get_function_defaults = operator.attrgetter(_func_defaults)605get_function_globals = operator.attrgetter(_func_globals)606607608if PY3:609610def iterkeys(d, **kw):611return iter(d.keys(**kw))612613def itervalues(d, **kw):614return iter(d.values(**kw))615616def iteritems(d, **kw):617return iter(d.items(**kw))618619def iterlists(d, **kw):620return iter(d.lists(**kw))621622viewkeys = operator.methodcaller("keys")623624viewvalues = operator.methodcaller("values")625626viewitems = operator.methodcaller("items")627else:628629def iterkeys(d, **kw):630return d.iterkeys(**kw)631632def itervalues(d, **kw):633return d.itervalues(**kw)634635def iteritems(d, **kw):636return d.iteritems(**kw)637638def iterlists(d, **kw):639return d.iterlists(**kw)640641viewkeys = operator.methodcaller("viewkeys")642643viewvalues = operator.methodcaller("viewvalues")644645viewitems = operator.methodcaller("viewitems")646647_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")648_add_doc(itervalues, "Return an iterator over the values of a dictionary.")649_add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.")650_add_doc(651iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary."652)653654655if PY3:656657def b(s):658return s.encode("latin-1")659660def u(s):661return s662663unichr = chr664import struct665666int2byte = struct.Struct(">B").pack667del struct668byte2int = operator.itemgetter(0)669indexbytes = operator.getitem670iterbytes = iter671import io672673StringIO = io.StringIO674BytesIO = io.BytesIO675del io676_assertCountEqual = "assertCountEqual"677if sys.version_info[1] <= 1:678_assertRaisesRegex = "assertRaisesRegexp"679_assertRegex = "assertRegexpMatches"680else:681_assertRaisesRegex = "assertRaisesRegex"682_assertRegex = "assertRegex"683else:684685def b(s):686return s687688# Workaround for standalone backslash689690def u(s):691return unicode(s.replace(r"\\", r"\\\\"), "unicode_escape")692693unichr = unichr694int2byte = chr695696def byte2int(bs):697return ord(bs[0])698699def indexbytes(buf, i):700return ord(buf[i])701702iterbytes = functools.partial(itertools.imap, ord)703import StringIO704705StringIO = BytesIO = StringIO.StringIO706_assertCountEqual = "assertItemsEqual"707_assertRaisesRegex = "assertRaisesRegexp"708_assertRegex = "assertRegexpMatches"709_add_doc(b, """Byte literal""")710_add_doc(u, """Text literal""")711712713def assertCountEqual(self, *args, **kwargs):714return getattr(self, _assertCountEqual)(*args, **kwargs)715716717def assertRaisesRegex(self, *args, **kwargs):718return getattr(self, _assertRaisesRegex)(*args, **kwargs)719720721def assertRegex(self, *args, **kwargs):722return getattr(self, _assertRegex)(*args, **kwargs)723724725if PY3:726exec_ = getattr(moves.builtins, "exec")727728def reraise(tp, value, tb=None):729try:730if value is None:731value = tp()732if value.__traceback__ is not tb:733raise value.with_traceback(tb)734raise value735finally:736value = None737tb = None738739740else:741742def exec_(_code_, _globs_=None, _locs_=None):743"""Execute code in a namespace."""744if _globs_ is None:745frame = sys._getframe(1)746_globs_ = frame.f_globals747if _locs_ is None:748_locs_ = frame.f_locals749del frame750elif _locs_ is None:751_locs_ = _globs_752exec("""exec _code_ in _globs_, _locs_""")753754exec_(755"""def reraise(tp, value, tb=None):756try:757raise tp, value, tb758finally:759tb = None760"""761)762763764if sys.version_info[:2] == (3, 2):765exec_(766"""def raise_from(value, from_value):767try:768if from_value is None:769raise value770raise value from from_value771finally:772value = None773"""774)775elif sys.version_info[:2] > (3, 2):776exec_(777"""def raise_from(value, from_value):778try:779raise value from from_value780finally:781value = None782"""783)784else:785786def raise_from(value, from_value):787raise value788789790print_ = getattr(moves.builtins, "print", None)791if print_ is None:792793def print_(*args, **kwargs):794"""The new-style print function for Python 2.4 and 2.5."""795fp = kwargs.pop("file", sys.stdout)796if fp is None:797return798799def write(data):800if not isinstance(data, basestring):801data = str(data)802# If the file has an encoding, encode unicode with it.803if (804isinstance(fp, file)805and isinstance(data, unicode)806and fp.encoding is not None807):808errors = getattr(fp, "errors", None)809if errors is None:810errors = "strict"811data = data.encode(fp.encoding, errors)812fp.write(data)813814want_unicode = False815sep = kwargs.pop("sep", None)816if sep is not None:817if isinstance(sep, unicode):818want_unicode = True819elif not isinstance(sep, str):820raise TypeError("sep must be None or a string")821end = kwargs.pop("end", None)822if end is not None:823if isinstance(end, unicode):824want_unicode = True825elif not isinstance(end, str):826raise TypeError("end must be None or a string")827if kwargs:828raise TypeError("invalid keyword arguments to print()")829if not want_unicode:830for arg in args:831if isinstance(arg, unicode):832want_unicode = True833break834if want_unicode:835newline = unicode("\n")836space = unicode(" ")837else:838newline = "\n"839space = " "840if sep is None:841sep = space842if end is None:843end = newline844for i, arg in enumerate(args):845if i:846write(sep)847write(arg)848write(end)849850851if sys.version_info[:2] < (3, 3):852_print = print_853854def print_(*args, **kwargs):855fp = kwargs.get("file", sys.stdout)856flush = kwargs.pop("flush", False)857_print(*args, **kwargs)858if flush and fp is not None:859fp.flush()860861862_add_doc(reraise, """Reraise an exception.""")863864if sys.version_info[0:2] < (3, 4):865866def wraps(867wrapped,868assigned=functools.WRAPPER_ASSIGNMENTS,869updated=functools.WRAPPER_UPDATES,870):871def wrapper(f):872f = functools.wraps(wrapped, assigned, updated)(f)873f.__wrapped__ = wrapped874return f875876return wrapper877878879else:880wraps = functools.wraps881882883def with_metaclass(meta, *bases):884"""Create a base class with a metaclass."""885# This requires a bit of explanation: the basic idea is to make a dummy886# metaclass for one level of class instantiation that replaces itself with887# the actual metaclass.888class metaclass(type):889def __new__(cls, name, this_bases, d):890return meta(name, bases, d)891892@classmethod893def __prepare__(cls, name, this_bases):894return meta.__prepare__(name, bases)895896return type.__new__(metaclass, "temporary_class", (), {})897898899def add_metaclass(metaclass):900"""Class decorator for creating a class with a metaclass."""901902def wrapper(cls):903orig_vars = cls.__dict__.copy()904slots = orig_vars.get("__slots__")905if slots is not None:906if isinstance(slots, str):907slots = [slots]908for slots_var in slots:909orig_vars.pop(slots_var)910orig_vars.pop("__dict__", None)911orig_vars.pop("__weakref__", None)912if hasattr(cls, "__qualname__"):913orig_vars["__qualname__"] = cls.__qualname__914return metaclass(cls.__name__, cls.__bases__, orig_vars)915916return wrapper917918919def ensure_binary(s, encoding="utf-8", errors="strict"):920"""Coerce **s** to six.binary_type.921922For Python 2:923- `unicode` -> encoded to `str`924- `str` -> `str`925926For Python 3:927- `str` -> encoded to `bytes`928- `bytes` -> `bytes`929"""930if isinstance(s, text_type):931return s.encode(encoding, errors)932elif isinstance(s, binary_type):933return s934else:935raise TypeError("not expecting type '%s'" % type(s))936937938def ensure_str(s, encoding="utf-8", errors="strict"):939"""Coerce *s* to `str`.940941For Python 2:942- `unicode` -> encoded to `str`943- `str` -> `str`944945For Python 3:946- `str` -> `str`947- `bytes` -> decoded to `str`948"""949if not isinstance(s, (text_type, binary_type)):950raise TypeError("not expecting type '%s'" % type(s))951if PY2 and isinstance(s, text_type):952s = s.encode(encoding, errors)953elif PY3 and isinstance(s, binary_type):954s = s.decode(encoding, errors)955return s956957958def ensure_text(s, encoding="utf-8", errors="strict"):959"""Coerce *s* to six.text_type.960961For Python 2:962- `unicode` -> `unicode`963- `str` -> `unicode`964965For Python 3:966- `str` -> `str`967- `bytes` -> decoded to `str`968"""969if isinstance(s, binary_type):970return s.decode(encoding, errors)971elif isinstance(s, text_type):972return s973else:974raise TypeError("not expecting type '%s'" % type(s))975976977def python_2_unicode_compatible(klass):978"""979A decorator that defines __unicode__ and __str__ methods under Python 2.980Under Python 3 it does nothing.981982To support Python 2 and 3 with a single code base, define a __str__ method983returning text and apply this decorator to the class.984"""985if PY2:986if "__str__" not in klass.__dict__:987raise ValueError(988"@python_2_unicode_compatible cannot be applied "989"to %s because it doesn't define __str__()." % klass.__name__990)991klass.__unicode__ = klass.__str__992klass.__str__ = lambda self: self.__unicode__().encode("utf-8")993return klass994995996# Complete the moves implementation.997# This code is at the end of this module to speed up module loading.998# Turn this module into a package.999__path__ = [] # required for PEP 302 and PEP 4511000__package__ = __name__ # see PEP 366 @ReservedAssignment1001if globals().get("__spec__") is not None:1002__spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable1003# Remove other six meta path importers, since they cause problems. This can1004# happen if six is removed from sys.modules and then reloaded. (Setuptools does1005# this for some reason.)1006if sys.meta_path:1007for i, importer in enumerate(sys.meta_path):1008# Here's some real nastiness: Another "instance" of the six module might1009# be floating around. Therefore, we can't use isinstance() to check for1010# the six meta path importer, since the other six instance will have1011# inserted an importer with different class.1012if (1013type(importer).__name__ == "_SixMetaPathImporter"1014and importer.name == __name__1015):1016del sys.meta_path[i]1017break1018del i, importer1019# Finally, add the importer to the meta path import hook.1020sys.meta_path.append(_importer)102110221023