Path: blob/master/venv/Lib/site-packages/pip/_vendor/six.py
811 views
# Copyright (c) 2010-2020 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.14.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):6061def __len__(self):62return 1 << 3163try: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):8687def __init__(self, name):88self.name = name8990def __get__(self, obj, tp):91result = self._resolve()92setattr(obj, self.name, result) # Invokes __set__.93try:94# This is a bit ugly, but it avoids running this again by95# removing this descriptor.96delattr(obj.__class__, self.name)97except AttributeError:98pass99return result100101102class MovedModule(_LazyDescr):103104def __init__(self, name, old, new=None):105super(MovedModule, self).__init__(name)106if PY3:107if new is None:108new = name109self.mod = new110else:111self.mod = old112113def _resolve(self):114return _import_module(self.mod)115116def __getattr__(self, attr):117_module = self._resolve()118value = getattr(_module, attr)119setattr(self, attr, value)120return value121122123class _LazyModule(types.ModuleType):124125def __init__(self, name):126super(_LazyModule, self).__init__(name)127self.__doc__ = self.__class__.__doc__128129def __dir__(self):130attrs = ["__doc__", "__name__"]131attrs += [attr.name for attr in self._moved_attributes]132return attrs133134# Subclasses should override this135_moved_attributes = []136137138class MovedAttribute(_LazyDescr):139140def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):141super(MovedAttribute, self).__init__(name)142if PY3:143if new_mod is None:144new_mod = name145self.mod = new_mod146if new_attr is None:147if old_attr is None:148new_attr = name149else:150new_attr = old_attr151self.attr = new_attr152else:153self.mod = old_mod154if old_attr is None:155old_attr = name156self.attr = old_attr157158def _resolve(self):159module = _import_module(self.mod)160return getattr(module, self.attr)161162163class _SixMetaPathImporter(object):164165"""166A meta path importer to import six.moves and its submodules.167168This class implements a PEP302 finder and loader. It should be compatible169with Python 2.5 and all existing versions of Python3170"""171172def __init__(self, six_module_name):173self.name = six_module_name174self.known_modules = {}175176def _add_module(self, mod, *fullnames):177for fullname in fullnames:178self.known_modules[self.name + "." + fullname] = mod179180def _get_module(self, fullname):181return self.known_modules[self.name + "." + fullname]182183def find_module(self, fullname, path=None):184if fullname in self.known_modules:185return self186return None187188def __get_module(self, fullname):189try:190return self.known_modules[fullname]191except KeyError:192raise ImportError("This loader does not know module " + fullname)193194def load_module(self, fullname):195try:196# in case of a reload197return sys.modules[fullname]198except KeyError:199pass200mod = self.__get_module(fullname)201if isinstance(mod, MovedModule):202mod = mod._resolve()203else:204mod.__loader__ = self205sys.modules[fullname] = mod206return mod207208def is_package(self, fullname):209"""210Return true, if the named module is a package.211212We need this method to get correct spec objects with213Python 3.4 (see PEP451)214"""215return hasattr(self.__get_module(fullname), "__path__")216217def get_code(self, fullname):218"""Return None219220Required, if is_package is implemented"""221self.__get_module(fullname) # eventually raises ImportError222return None223get_source = get_code # same as get_code224225_importer = _SixMetaPathImporter(__name__)226227228class _MovedItems(_LazyModule):229230"""Lazy loading of moved objects"""231__path__ = [] # mark as package232233234_moved_attributes = [235MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),236MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),237MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),238MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),239MovedAttribute("intern", "__builtin__", "sys"),240MovedAttribute("map", "itertools", "builtins", "imap", "map"),241MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"),242MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"),243MovedAttribute("getoutput", "commands", "subprocess"),244MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),245MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"),246MovedAttribute("reduce", "__builtin__", "functools"),247MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),248MovedAttribute("StringIO", "StringIO", "io"),249MovedAttribute("UserDict", "UserDict", "collections"),250MovedAttribute("UserList", "UserList", "collections"),251MovedAttribute("UserString", "UserString", "collections"),252MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),253MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),254MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),255MovedModule("builtins", "__builtin__"),256MovedModule("configparser", "ConfigParser"),257MovedModule("collections_abc", "collections", "collections.abc" if sys.version_info >= (3, 3) else "collections"),258MovedModule("copyreg", "copy_reg"),259MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),260MovedModule("dbm_ndbm", "dbm", "dbm.ndbm"),261MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread" if sys.version_info < (3, 9) else "_thread"),262MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),263MovedModule("http_cookies", "Cookie", "http.cookies"),264MovedModule("html_entities", "htmlentitydefs", "html.entities"),265MovedModule("html_parser", "HTMLParser", "html.parser"),266MovedModule("http_client", "httplib", "http.client"),267MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),268MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"),269MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),270MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"),271MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),272MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),273MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),274MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),275MovedModule("cPickle", "cPickle", "pickle"),276MovedModule("queue", "Queue"),277MovedModule("reprlib", "repr"),278MovedModule("socketserver", "SocketServer"),279MovedModule("_thread", "thread", "_thread"),280MovedModule("tkinter", "Tkinter"),281MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),282MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),283MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),284MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),285MovedModule("tkinter_tix", "Tix", "tkinter.tix"),286MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),287MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),288MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),289MovedModule("tkinter_colorchooser", "tkColorChooser",290"tkinter.colorchooser"),291MovedModule("tkinter_commondialog", "tkCommonDialog",292"tkinter.commondialog"),293MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),294MovedModule("tkinter_font", "tkFont", "tkinter.font"),295MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),296MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",297"tkinter.simpledialog"),298MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),299MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),300MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),301MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),302MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),303MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),304]305# Add windows specific modules.306if sys.platform == "win32":307_moved_attributes += [308MovedModule("winreg", "_winreg"),309]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("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"),344MovedAttribute("urlencode", "urllib", "urllib.parse"),345MovedAttribute("splitquery", "urllib", "urllib.parse"),346MovedAttribute("splittag", "urllib", "urllib.parse"),347MovedAttribute("splituser", "urllib", "urllib.parse"),348MovedAttribute("splitvalue", "urllib", "urllib.parse"),349MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),350MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),351MovedAttribute("uses_params", "urlparse", "urllib.parse"),352MovedAttribute("uses_query", "urlparse", "urllib.parse"),353MovedAttribute("uses_relative", "urlparse", "urllib.parse"),354]355for attr in _urllib_parse_moved_attributes:356setattr(Module_six_moves_urllib_parse, attr.name, attr)357del attr358359Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes360361_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),362"moves.urllib_parse", "moves.urllib.parse")363364365class Module_six_moves_urllib_error(_LazyModule):366367"""Lazy loading of moved objects in six.moves.urllib_error"""368369370_urllib_error_moved_attributes = [371MovedAttribute("URLError", "urllib2", "urllib.error"),372MovedAttribute("HTTPError", "urllib2", "urllib.error"),373MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),374]375for attr in _urllib_error_moved_attributes:376setattr(Module_six_moves_urllib_error, attr.name, attr)377del attr378379Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes380381_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),382"moves.urllib_error", "moves.urllib.error")383384385class Module_six_moves_urllib_request(_LazyModule):386387"""Lazy loading of moved objects in six.moves.urllib_request"""388389390_urllib_request_moved_attributes = [391MovedAttribute("urlopen", "urllib2", "urllib.request"),392MovedAttribute("install_opener", "urllib2", "urllib.request"),393MovedAttribute("build_opener", "urllib2", "urllib.request"),394MovedAttribute("pathname2url", "urllib", "urllib.request"),395MovedAttribute("url2pathname", "urllib", "urllib.request"),396MovedAttribute("getproxies", "urllib", "urllib.request"),397MovedAttribute("Request", "urllib2", "urllib.request"),398MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),399MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),400MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),401MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),402MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),403MovedAttribute("BaseHandler", "urllib2", "urllib.request"),404MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),405MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),406MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),407MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),408MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),409MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),410MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),411MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),412MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),413MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),414MovedAttribute("FileHandler", "urllib2", "urllib.request"),415MovedAttribute("FTPHandler", "urllib2", "urllib.request"),416MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),417MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),418MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),419MovedAttribute("urlretrieve", "urllib", "urllib.request"),420MovedAttribute("urlcleanup", "urllib", "urllib.request"),421MovedAttribute("URLopener", "urllib", "urllib.request"),422MovedAttribute("FancyURLopener", "urllib", "urllib.request"),423MovedAttribute("proxy_bypass", "urllib", "urllib.request"),424MovedAttribute("parse_http_list", "urllib2", "urllib.request"),425MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"),426]427for attr in _urllib_request_moved_attributes:428setattr(Module_six_moves_urllib_request, attr.name, attr)429del attr430431Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes432433_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),434"moves.urllib_request", "moves.urllib.request")435436437class Module_six_moves_urllib_response(_LazyModule):438439"""Lazy loading of moved objects in six.moves.urllib_response"""440441442_urllib_response_moved_attributes = [443MovedAttribute("addbase", "urllib", "urllib.response"),444MovedAttribute("addclosehook", "urllib", "urllib.response"),445MovedAttribute("addinfo", "urllib", "urllib.response"),446MovedAttribute("addinfourl", "urllib", "urllib.response"),447]448for attr in _urllib_response_moved_attributes:449setattr(Module_six_moves_urllib_response, attr.name, attr)450del attr451452Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes453454_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),455"moves.urllib_response", "moves.urllib.response")456457458class Module_six_moves_urllib_robotparser(_LazyModule):459460"""Lazy loading of moved objects in six.moves.urllib_robotparser"""461462463_urllib_robotparser_moved_attributes = [464MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),465]466for attr in _urllib_robotparser_moved_attributes:467setattr(Module_six_moves_urllib_robotparser, attr.name, attr)468del attr469470Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes471472_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),473"moves.urllib_robotparser", "moves.urllib.robotparser")474475476class Module_six_moves_urllib(types.ModuleType):477478"""Create a six.moves.urllib namespace that resembles the Python 3 namespace"""479__path__ = [] # mark as package480parse = _importer._get_module("moves.urllib_parse")481error = _importer._get_module("moves.urllib_error")482request = _importer._get_module("moves.urllib_request")483response = _importer._get_module("moves.urllib_response")484robotparser = _importer._get_module("moves.urllib_robotparser")485486def __dir__(self):487return ['parse', 'error', 'request', 'response', 'robotparser']488489_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),490"moves.urllib")491492493def add_move(move):494"""Add an item to six.moves."""495setattr(_MovedItems, move.name, move)496497498def remove_move(name):499"""Remove item from six.moves."""500try:501delattr(_MovedItems, name)502except AttributeError:503try:504del moves.__dict__[name]505except KeyError:506raise AttributeError("no such move, %r" % (name,))507508509if PY3:510_meth_func = "__func__"511_meth_self = "__self__"512513_func_closure = "__closure__"514_func_code = "__code__"515_func_defaults = "__defaults__"516_func_globals = "__globals__"517else:518_meth_func = "im_func"519_meth_self = "im_self"520521_func_closure = "func_closure"522_func_code = "func_code"523_func_defaults = "func_defaults"524_func_globals = "func_globals"525526527try:528advance_iterator = next529except NameError:530def advance_iterator(it):531return it.next()532next = advance_iterator533534535try:536callable = callable537except NameError:538def callable(obj):539return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)540541542if PY3:543def get_unbound_function(unbound):544return unbound545546create_bound_method = types.MethodType547548def create_unbound_method(func, cls):549return func550551Iterator = object552else:553def get_unbound_function(unbound):554return unbound.im_func555556def create_bound_method(func, obj):557return types.MethodType(func, obj, obj.__class__)558559def create_unbound_method(func, cls):560return types.MethodType(func, None, cls)561562class Iterator(object):563564def next(self):565return type(self).__next__(self)566567callable = callable568_add_doc(get_unbound_function,569"""Get the function out of a possibly unbound function""")570571572get_method_function = operator.attrgetter(_meth_func)573get_method_self = operator.attrgetter(_meth_self)574get_function_closure = operator.attrgetter(_func_closure)575get_function_code = operator.attrgetter(_func_code)576get_function_defaults = operator.attrgetter(_func_defaults)577get_function_globals = operator.attrgetter(_func_globals)578579580if PY3:581def iterkeys(d, **kw):582return iter(d.keys(**kw))583584def itervalues(d, **kw):585return iter(d.values(**kw))586587def iteritems(d, **kw):588return iter(d.items(**kw))589590def iterlists(d, **kw):591return iter(d.lists(**kw))592593viewkeys = operator.methodcaller("keys")594595viewvalues = operator.methodcaller("values")596597viewitems = operator.methodcaller("items")598else:599def iterkeys(d, **kw):600return d.iterkeys(**kw)601602def itervalues(d, **kw):603return d.itervalues(**kw)604605def iteritems(d, **kw):606return d.iteritems(**kw)607608def iterlists(d, **kw):609return d.iterlists(**kw)610611viewkeys = operator.methodcaller("viewkeys")612613viewvalues = operator.methodcaller("viewvalues")614615viewitems = operator.methodcaller("viewitems")616617_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")618_add_doc(itervalues, "Return an iterator over the values of a dictionary.")619_add_doc(iteritems,620"Return an iterator over the (key, value) pairs of a dictionary.")621_add_doc(iterlists,622"Return an iterator over the (key, [values]) pairs of a dictionary.")623624625if PY3:626def b(s):627return s.encode("latin-1")628629def u(s):630return s631unichr = chr632import struct633int2byte = struct.Struct(">B").pack634del struct635byte2int = operator.itemgetter(0)636indexbytes = operator.getitem637iterbytes = iter638import io639StringIO = io.StringIO640BytesIO = io.BytesIO641del io642_assertCountEqual = "assertCountEqual"643if sys.version_info[1] <= 1:644_assertRaisesRegex = "assertRaisesRegexp"645_assertRegex = "assertRegexpMatches"646_assertNotRegex = "assertNotRegexpMatches"647else:648_assertRaisesRegex = "assertRaisesRegex"649_assertRegex = "assertRegex"650_assertNotRegex = "assertNotRegex"651else:652def b(s):653return s654# Workaround for standalone backslash655656def u(s):657return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")658unichr = unichr659int2byte = chr660661def byte2int(bs):662return ord(bs[0])663664def indexbytes(buf, i):665return ord(buf[i])666iterbytes = functools.partial(itertools.imap, ord)667import StringIO668StringIO = BytesIO = StringIO.StringIO669_assertCountEqual = "assertItemsEqual"670_assertRaisesRegex = "assertRaisesRegexp"671_assertRegex = "assertRegexpMatches"672_assertNotRegex = "assertNotRegexpMatches"673_add_doc(b, """Byte literal""")674_add_doc(u, """Text literal""")675676677def assertCountEqual(self, *args, **kwargs):678return getattr(self, _assertCountEqual)(*args, **kwargs)679680681def assertRaisesRegex(self, *args, **kwargs):682return getattr(self, _assertRaisesRegex)(*args, **kwargs)683684685def assertRegex(self, *args, **kwargs):686return getattr(self, _assertRegex)(*args, **kwargs)687688689def assertNotRegex(self, *args, **kwargs):690return getattr(self, _assertNotRegex)(*args, **kwargs)691692693if PY3:694exec_ = getattr(moves.builtins, "exec")695696def reraise(tp, value, tb=None):697try:698if value is None:699value = tp()700if value.__traceback__ is not tb:701raise value.with_traceback(tb)702raise value703finally:704value = None705tb = None706707else:708def exec_(_code_, _globs_=None, _locs_=None):709"""Execute code in a namespace."""710if _globs_ is None:711frame = sys._getframe(1)712_globs_ = frame.f_globals713if _locs_ is None:714_locs_ = frame.f_locals715del frame716elif _locs_ is None:717_locs_ = _globs_718exec("""exec _code_ in _globs_, _locs_""")719720exec_("""def reraise(tp, value, tb=None):721try:722raise tp, value, tb723finally:724tb = None725""")726727728if sys.version_info[:2] > (3,):729exec_("""def raise_from(value, from_value):730try:731raise value from from_value732finally:733value = None734""")735else:736def raise_from(value, from_value):737raise value738739740print_ = getattr(moves.builtins, "print", None)741if print_ is None:742def print_(*args, **kwargs):743"""The new-style print function for Python 2.4 and 2.5."""744fp = kwargs.pop("file", sys.stdout)745if fp is None:746return747748def write(data):749if not isinstance(data, basestring):750data = str(data)751# If the file has an encoding, encode unicode with it.752if (isinstance(fp, file) and753isinstance(data, unicode) and754fp.encoding is not None):755errors = getattr(fp, "errors", None)756if errors is None:757errors = "strict"758data = data.encode(fp.encoding, errors)759fp.write(data)760want_unicode = False761sep = kwargs.pop("sep", None)762if sep is not None:763if isinstance(sep, unicode):764want_unicode = True765elif not isinstance(sep, str):766raise TypeError("sep must be None or a string")767end = kwargs.pop("end", None)768if end is not None:769if isinstance(end, unicode):770want_unicode = True771elif not isinstance(end, str):772raise TypeError("end must be None or a string")773if kwargs:774raise TypeError("invalid keyword arguments to print()")775if not want_unicode:776for arg in args:777if isinstance(arg, unicode):778want_unicode = True779break780if want_unicode:781newline = unicode("\n")782space = unicode(" ")783else:784newline = "\n"785space = " "786if sep is None:787sep = space788if end is None:789end = newline790for i, arg in enumerate(args):791if i:792write(sep)793write(arg)794write(end)795if sys.version_info[:2] < (3, 3):796_print = print_797798def print_(*args, **kwargs):799fp = kwargs.get("file", sys.stdout)800flush = kwargs.pop("flush", False)801_print(*args, **kwargs)802if flush and fp is not None:803fp.flush()804805_add_doc(reraise, """Reraise an exception.""")806807if sys.version_info[0:2] < (3, 4):808# This does exactly the same what the :func:`py3:functools.update_wrapper`809# function does on Python versions after 3.2. It sets the ``__wrapped__``810# attribute on ``wrapper`` object and it doesn't raise an error if any of811# the attributes mentioned in ``assigned`` and ``updated`` are missing on812# ``wrapped`` object.813def _update_wrapper(wrapper, wrapped,814assigned=functools.WRAPPER_ASSIGNMENTS,815updated=functools.WRAPPER_UPDATES):816for attr in assigned:817try:818value = getattr(wrapped, attr)819except AttributeError:820continue821else:822setattr(wrapper, attr, value)823for attr in updated:824getattr(wrapper, attr).update(getattr(wrapped, attr, {}))825wrapper.__wrapped__ = wrapped826return wrapper827_update_wrapper.__doc__ = functools.update_wrapper.__doc__828829def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,830updated=functools.WRAPPER_UPDATES):831return functools.partial(_update_wrapper, wrapped=wrapped,832assigned=assigned, updated=updated)833wraps.__doc__ = functools.wraps.__doc__834835else:836wraps = functools.wraps837838839def with_metaclass(meta, *bases):840"""Create a base class with a metaclass."""841# This requires a bit of explanation: the basic idea is to make a dummy842# metaclass for one level of class instantiation that replaces itself with843# the actual metaclass.844class metaclass(type):845846def __new__(cls, name, this_bases, d):847if sys.version_info[:2] >= (3, 7):848# This version introduced PEP 560 that requires a bit849# of extra care (we mimic what is done by __build_class__).850resolved_bases = types.resolve_bases(bases)851if resolved_bases is not bases:852d['__orig_bases__'] = bases853else:854resolved_bases = bases855return meta(name, resolved_bases, d)856857@classmethod858def __prepare__(cls, name, this_bases):859return meta.__prepare__(name, bases)860return type.__new__(metaclass, 'temporary_class', (), {})861862863def add_metaclass(metaclass):864"""Class decorator for creating a class with a metaclass."""865def wrapper(cls):866orig_vars = cls.__dict__.copy()867slots = orig_vars.get('__slots__')868if slots is not None:869if isinstance(slots, str):870slots = [slots]871for slots_var in slots:872orig_vars.pop(slots_var)873orig_vars.pop('__dict__', None)874orig_vars.pop('__weakref__', None)875if hasattr(cls, '__qualname__'):876orig_vars['__qualname__'] = cls.__qualname__877return metaclass(cls.__name__, cls.__bases__, orig_vars)878return wrapper879880881def ensure_binary(s, encoding='utf-8', errors='strict'):882"""Coerce **s** to six.binary_type.883884For Python 2:885- `unicode` -> encoded to `str`886- `str` -> `str`887888For Python 3:889- `str` -> encoded to `bytes`890- `bytes` -> `bytes`891"""892if isinstance(s, text_type):893return s.encode(encoding, errors)894elif isinstance(s, binary_type):895return s896else:897raise TypeError("not expecting type '%s'" % type(s))898899900def ensure_str(s, encoding='utf-8', errors='strict'):901"""Coerce *s* to `str`.902903For Python 2:904- `unicode` -> encoded to `str`905- `str` -> `str`906907For Python 3:908- `str` -> `str`909- `bytes` -> decoded to `str`910"""911if not isinstance(s, (text_type, binary_type)):912raise TypeError("not expecting type '%s'" % type(s))913if PY2 and isinstance(s, text_type):914s = s.encode(encoding, errors)915elif PY3 and isinstance(s, binary_type):916s = s.decode(encoding, errors)917return s918919920def ensure_text(s, encoding='utf-8', errors='strict'):921"""Coerce *s* to six.text_type.922923For Python 2:924- `unicode` -> `unicode`925- `str` -> `unicode`926927For Python 3:928- `str` -> `str`929- `bytes` -> decoded to `str`930"""931if isinstance(s, binary_type):932return s.decode(encoding, errors)933elif isinstance(s, text_type):934return s935else:936raise TypeError("not expecting type '%s'" % type(s))937938939def python_2_unicode_compatible(klass):940"""941A class decorator that defines __unicode__ and __str__ methods under Python 2.942Under Python 3 it does nothing.943944To support Python 2 and 3 with a single code base, define a __str__ method945returning text and apply this decorator to the class.946"""947if PY2:948if '__str__' not in klass.__dict__:949raise ValueError("@python_2_unicode_compatible cannot be applied "950"to %s because it doesn't define __str__()." %951klass.__name__)952klass.__unicode__ = klass.__str__953klass.__str__ = lambda self: self.__unicode__().encode('utf-8')954return klass955956957# Complete the moves implementation.958# This code is at the end of this module to speed up module loading.959# Turn this module into a package.960__path__ = [] # required for PEP 302 and PEP 451961__package__ = __name__ # see PEP 366 @ReservedAssignment962if globals().get("__spec__") is not None:963__spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable964# Remove other six meta path importers, since they cause problems. This can965# happen if six is removed from sys.modules and then reloaded. (Setuptools does966# this for some reason.)967if sys.meta_path:968for i, importer in enumerate(sys.meta_path):969# Here's some real nastiness: Another "instance" of the six module might970# be floating around. Therefore, we can't use isinstance() to check for971# the six meta path importer, since the other six instance will have972# inserted an importer with different class.973if (type(importer).__name__ == "_SixMetaPathImporter" and974importer.name == __name__):975del sys.meta_path[i]976break977del i, importer978# Finally, add the importer to the meta path import hook.979sys.meta_path.append(_importer)980981982