Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/six.py
5931 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.16.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 X7273if PY34:74from importlib.util import spec_from_loader75else:76spec_from_loader = None777879def _add_doc(func, doc):80"""Add documentation to a function."""81func.__doc__ = doc828384def _import_module(name):85"""Import module, returning the module after the last dot."""86__import__(name)87return sys.modules[name]888990class _LazyDescr(object):9192def __init__(self, name):93self.name = name9495def __get__(self, obj, tp):96result = self._resolve()97setattr(obj, self.name, result) # Invokes __set__.98try:99# This is a bit ugly, but it avoids running this again by100# removing this descriptor.101delattr(obj.__class__, self.name)102except AttributeError:103pass104return result105106107class MovedModule(_LazyDescr):108109def __init__(self, name, old, new=None):110super(MovedModule, self).__init__(name)111if PY3:112if new is None:113new = name114self.mod = new115else:116self.mod = old117118def _resolve(self):119return _import_module(self.mod)120121def __getattr__(self, attr):122_module = self._resolve()123value = getattr(_module, attr)124setattr(self, attr, value)125return value126127128class _LazyModule(types.ModuleType):129130def __init__(self, name):131super(_LazyModule, self).__init__(name)132self.__doc__ = self.__class__.__doc__133134def __dir__(self):135attrs = ["__doc__", "__name__"]136attrs += [attr.name for attr in self._moved_attributes]137return attrs138139# Subclasses should override this140_moved_attributes = []141142143class MovedAttribute(_LazyDescr):144145def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):146super(MovedAttribute, self).__init__(name)147if PY3:148if new_mod is None:149new_mod = name150self.mod = new_mod151if new_attr is None:152if old_attr is None:153new_attr = name154else:155new_attr = old_attr156self.attr = new_attr157else:158self.mod = old_mod159if old_attr is None:160old_attr = name161self.attr = old_attr162163def _resolve(self):164module = _import_module(self.mod)165return getattr(module, self.attr)166167168class _SixMetaPathImporter(object):169170"""171A meta path importer to import six.moves and its submodules.172173This class implements a PEP302 finder and loader. It should be compatible174with Python 2.5 and all existing versions of Python3175"""176177def __init__(self, six_module_name):178self.name = six_module_name179self.known_modules = {}180181def _add_module(self, mod, *fullnames):182for fullname in fullnames:183self.known_modules[self.name + "." + fullname] = mod184185def _get_module(self, fullname):186return self.known_modules[self.name + "." + fullname]187188def find_module(self, fullname, path=None):189if fullname in self.known_modules:190return self191return None192193def find_spec(self, fullname, path, target=None):194if fullname in self.known_modules:195return spec_from_loader(fullname, self)196return None197198def __get_module(self, fullname):199try:200return self.known_modules[fullname]201except KeyError:202raise ImportError("This loader does not know module " + fullname)203204def load_module(self, fullname):205try:206# in case of a reload207return sys.modules[fullname]208except KeyError:209pass210mod = self.__get_module(fullname)211if isinstance(mod, MovedModule):212mod = mod._resolve()213else:214mod.__loader__ = self215sys.modules[fullname] = mod216return mod217218def is_package(self, fullname):219"""220Return true, if the named module is a package.221222We need this method to get correct spec objects with223Python 3.4 (see PEP451)224"""225return hasattr(self.__get_module(fullname), "__path__")226227def get_code(self, fullname):228"""Return None229230Required, if is_package is implemented"""231self.__get_module(fullname) # eventually raises ImportError232return None233get_source = get_code # same as get_code234235def create_module(self, spec):236return self.load_module(spec.name)237238def exec_module(self, module):239pass240241_importer = _SixMetaPathImporter(__name__)242243244class _MovedItems(_LazyModule):245246"""Lazy loading of moved objects"""247__path__ = [] # mark as package248249250_moved_attributes = [251MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),252MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),253MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),254MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),255MovedAttribute("intern", "__builtin__", "sys"),256MovedAttribute("map", "itertools", "builtins", "imap", "map"),257MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"),258MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"),259MovedAttribute("getoutput", "commands", "subprocess"),260MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),261MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"),262MovedAttribute("reduce", "__builtin__", "functools"),263MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),264MovedAttribute("StringIO", "StringIO", "io"),265MovedAttribute("UserDict", "UserDict", "collections"),266MovedAttribute("UserList", "UserList", "collections"),267MovedAttribute("UserString", "UserString", "collections"),268MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),269MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),270MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),271MovedModule("builtins", "__builtin__"),272MovedModule("configparser", "ConfigParser"),273MovedModule("collections_abc", "collections", "collections.abc" if sys.version_info >= (3, 3) else "collections"),274MovedModule("copyreg", "copy_reg"),275MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),276MovedModule("dbm_ndbm", "dbm", "dbm.ndbm"),277MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread" if sys.version_info < (3, 9) else "_thread"),278MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),279MovedModule("http_cookies", "Cookie", "http.cookies"),280MovedModule("html_entities", "htmlentitydefs", "html.entities"),281MovedModule("html_parser", "HTMLParser", "html.parser"),282MovedModule("http_client", "httplib", "http.client"),283MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),284MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"),285MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),286MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"),287MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),288MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),289MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),290MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),291MovedModule("cPickle", "cPickle", "pickle"),292MovedModule("queue", "Queue"),293MovedModule("reprlib", "repr"),294MovedModule("socketserver", "SocketServer"),295MovedModule("_thread", "thread", "_thread"),296MovedModule("tkinter", "Tkinter"),297MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),298MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),299MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),300MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),301MovedModule("tkinter_tix", "Tix", "tkinter.tix"),302MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),303MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),304MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),305MovedModule("tkinter_colorchooser", "tkColorChooser",306"tkinter.colorchooser"),307MovedModule("tkinter_commondialog", "tkCommonDialog",308"tkinter.commondialog"),309MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),310MovedModule("tkinter_font", "tkFont", "tkinter.font"),311MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),312MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",313"tkinter.simpledialog"),314MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),315MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),316MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),317MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),318MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),319MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),320]321# Add windows specific modules.322if sys.platform == "win32":323_moved_attributes += [324MovedModule("winreg", "_winreg"),325]326327for attr in _moved_attributes:328setattr(_MovedItems, attr.name, attr)329if isinstance(attr, MovedModule):330_importer._add_module(attr, "moves." + attr.name)331del attr332333_MovedItems._moved_attributes = _moved_attributes334335moves = _MovedItems(__name__ + ".moves")336_importer._add_module(moves, "moves")337338339class Module_six_moves_urllib_parse(_LazyModule):340341"""Lazy loading of moved objects in six.moves.urllib_parse"""342343344_urllib_parse_moved_attributes = [345MovedAttribute("ParseResult", "urlparse", "urllib.parse"),346MovedAttribute("SplitResult", "urlparse", "urllib.parse"),347MovedAttribute("parse_qs", "urlparse", "urllib.parse"),348MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),349MovedAttribute("urldefrag", "urlparse", "urllib.parse"),350MovedAttribute("urljoin", "urlparse", "urllib.parse"),351MovedAttribute("urlparse", "urlparse", "urllib.parse"),352MovedAttribute("urlsplit", "urlparse", "urllib.parse"),353MovedAttribute("urlunparse", "urlparse", "urllib.parse"),354MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),355MovedAttribute("quote", "urllib", "urllib.parse"),356MovedAttribute("quote_plus", "urllib", "urllib.parse"),357MovedAttribute("unquote", "urllib", "urllib.parse"),358MovedAttribute("unquote_plus", "urllib", "urllib.parse"),359MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"),360MovedAttribute("urlencode", "urllib", "urllib.parse"),361MovedAttribute("splitquery", "urllib", "urllib.parse"),362MovedAttribute("splittag", "urllib", "urllib.parse"),363MovedAttribute("splituser", "urllib", "urllib.parse"),364MovedAttribute("splitvalue", "urllib", "urllib.parse"),365MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),366MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),367MovedAttribute("uses_params", "urlparse", "urllib.parse"),368MovedAttribute("uses_query", "urlparse", "urllib.parse"),369MovedAttribute("uses_relative", "urlparse", "urllib.parse"),370]371for attr in _urllib_parse_moved_attributes:372setattr(Module_six_moves_urllib_parse, attr.name, attr)373del attr374375Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes376377_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),378"moves.urllib_parse", "moves.urllib.parse")379380381class Module_six_moves_urllib_error(_LazyModule):382383"""Lazy loading of moved objects in six.moves.urllib_error"""384385386_urllib_error_moved_attributes = [387MovedAttribute("URLError", "urllib2", "urllib.error"),388MovedAttribute("HTTPError", "urllib2", "urllib.error"),389MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),390]391for attr in _urllib_error_moved_attributes:392setattr(Module_six_moves_urllib_error, attr.name, attr)393del attr394395Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes396397_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),398"moves.urllib_error", "moves.urllib.error")399400401class Module_six_moves_urllib_request(_LazyModule):402403"""Lazy loading of moved objects in six.moves.urllib_request"""404405406_urllib_request_moved_attributes = [407MovedAttribute("urlopen", "urllib2", "urllib.request"),408MovedAttribute("install_opener", "urllib2", "urllib.request"),409MovedAttribute("build_opener", "urllib2", "urllib.request"),410MovedAttribute("pathname2url", "urllib", "urllib.request"),411MovedAttribute("url2pathname", "urllib", "urllib.request"),412MovedAttribute("getproxies", "urllib", "urllib.request"),413MovedAttribute("Request", "urllib2", "urllib.request"),414MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),415MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),416MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),417MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),418MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),419MovedAttribute("BaseHandler", "urllib2", "urllib.request"),420MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),421MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),422MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),423MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),424MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),425MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),426MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),427MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),428MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),429MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),430MovedAttribute("FileHandler", "urllib2", "urllib.request"),431MovedAttribute("FTPHandler", "urllib2", "urllib.request"),432MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),433MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),434MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),435MovedAttribute("urlretrieve", "urllib", "urllib.request"),436MovedAttribute("urlcleanup", "urllib", "urllib.request"),437MovedAttribute("URLopener", "urllib", "urllib.request"),438MovedAttribute("FancyURLopener", "urllib", "urllib.request"),439MovedAttribute("proxy_bypass", "urllib", "urllib.request"),440MovedAttribute("parse_http_list", "urllib2", "urllib.request"),441MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"),442]443for attr in _urllib_request_moved_attributes:444setattr(Module_six_moves_urllib_request, attr.name, attr)445del attr446447Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes448449_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),450"moves.urllib_request", "moves.urllib.request")451452453class Module_six_moves_urllib_response(_LazyModule):454455"""Lazy loading of moved objects in six.moves.urllib_response"""456457458_urllib_response_moved_attributes = [459MovedAttribute("addbase", "urllib", "urllib.response"),460MovedAttribute("addclosehook", "urllib", "urllib.response"),461MovedAttribute("addinfo", "urllib", "urllib.response"),462MovedAttribute("addinfourl", "urllib", "urllib.response"),463]464for attr in _urllib_response_moved_attributes:465setattr(Module_six_moves_urllib_response, attr.name, attr)466del attr467468Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes469470_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),471"moves.urllib_response", "moves.urllib.response")472473474class Module_six_moves_urllib_robotparser(_LazyModule):475476"""Lazy loading of moved objects in six.moves.urllib_robotparser"""477478479_urllib_robotparser_moved_attributes = [480MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),481]482for attr in _urllib_robotparser_moved_attributes:483setattr(Module_six_moves_urllib_robotparser, attr.name, attr)484del attr485486Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes487488_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),489"moves.urllib_robotparser", "moves.urllib.robotparser")490491492class Module_six_moves_urllib(types.ModuleType):493494"""Create a six.moves.urllib namespace that resembles the Python 3 namespace"""495__path__ = [] # mark as package496parse = _importer._get_module("moves.urllib_parse")497error = _importer._get_module("moves.urllib_error")498request = _importer._get_module("moves.urllib_request")499response = _importer._get_module("moves.urllib_response")500robotparser = _importer._get_module("moves.urllib_robotparser")501502def __dir__(self):503return ['parse', 'error', 'request', 'response', 'robotparser']504505_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),506"moves.urllib")507508509def add_move(move):510"""Add an item to six.moves."""511setattr(_MovedItems, move.name, move)512513514def remove_move(name):515"""Remove item from six.moves."""516try:517delattr(_MovedItems, name)518except AttributeError:519try:520del moves.__dict__[name]521except KeyError:522raise AttributeError("no such move, %r" % (name,))523524525if PY3:526_meth_func = "__func__"527_meth_self = "__self__"528529_func_closure = "__closure__"530_func_code = "__code__"531_func_defaults = "__defaults__"532_func_globals = "__globals__"533else:534_meth_func = "im_func"535_meth_self = "im_self"536537_func_closure = "func_closure"538_func_code = "func_code"539_func_defaults = "func_defaults"540_func_globals = "func_globals"541542543try:544advance_iterator = next545except NameError:546def advance_iterator(it):547return it.next()548next = advance_iterator549550551try:552callable = callable553except NameError:554def callable(obj):555return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)556557558if PY3:559def get_unbound_function(unbound):560return unbound561562create_bound_method = types.MethodType563564def create_unbound_method(func, cls):565return func566567Iterator = object568else:569def get_unbound_function(unbound):570return unbound.im_func571572def create_bound_method(func, obj):573return types.MethodType(func, obj, obj.__class__)574575def create_unbound_method(func, cls):576return types.MethodType(func, None, cls)577578class Iterator(object):579580def next(self):581return type(self).__next__(self)582583callable = callable584_add_doc(get_unbound_function,585"""Get the function out of a possibly unbound function""")586587588get_method_function = operator.attrgetter(_meth_func)589get_method_self = operator.attrgetter(_meth_self)590get_function_closure = operator.attrgetter(_func_closure)591get_function_code = operator.attrgetter(_func_code)592get_function_defaults = operator.attrgetter(_func_defaults)593get_function_globals = operator.attrgetter(_func_globals)594595596if PY3:597def iterkeys(d, **kw):598return iter(d.keys(**kw))599600def itervalues(d, **kw):601return iter(d.values(**kw))602603def iteritems(d, **kw):604return iter(d.items(**kw))605606def iterlists(d, **kw):607return iter(d.lists(**kw))608609viewkeys = operator.methodcaller("keys")610611viewvalues = operator.methodcaller("values")612613viewitems = operator.methodcaller("items")614else:615def iterkeys(d, **kw):616return d.iterkeys(**kw)617618def itervalues(d, **kw):619return d.itervalues(**kw)620621def iteritems(d, **kw):622return d.iteritems(**kw)623624def iterlists(d, **kw):625return d.iterlists(**kw)626627viewkeys = operator.methodcaller("viewkeys")628629viewvalues = operator.methodcaller("viewvalues")630631viewitems = operator.methodcaller("viewitems")632633_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")634_add_doc(itervalues, "Return an iterator over the values of a dictionary.")635_add_doc(iteritems,636"Return an iterator over the (key, value) pairs of a dictionary.")637_add_doc(iterlists,638"Return an iterator over the (key, [values]) pairs of a dictionary.")639640641if PY3:642def b(s):643return s.encode("latin-1")644645def u(s):646return s647unichr = chr648import struct649int2byte = struct.Struct(">B").pack650del struct651byte2int = operator.itemgetter(0)652indexbytes = operator.getitem653iterbytes = iter654import io655StringIO = io.StringIO656BytesIO = io.BytesIO657del io658_assertCountEqual = "assertCountEqual"659if sys.version_info[1] <= 1:660_assertRaisesRegex = "assertRaisesRegexp"661_assertRegex = "assertRegexpMatches"662_assertNotRegex = "assertNotRegexpMatches"663else:664_assertRaisesRegex = "assertRaisesRegex"665_assertRegex = "assertRegex"666_assertNotRegex = "assertNotRegex"667else:668def b(s):669return s670# Workaround for standalone backslash671672def u(s):673return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")674unichr = unichr675int2byte = chr676677def byte2int(bs):678return ord(bs[0])679680def indexbytes(buf, i):681return ord(buf[i])682iterbytes = functools.partial(itertools.imap, ord)683import StringIO684StringIO = BytesIO = StringIO.StringIO685_assertCountEqual = "assertItemsEqual"686_assertRaisesRegex = "assertRaisesRegexp"687_assertRegex = "assertRegexpMatches"688_assertNotRegex = "assertNotRegexpMatches"689_add_doc(b, """Byte literal""")690_add_doc(u, """Text literal""")691692693def assertCountEqual(self, *args, **kwargs):694return getattr(self, _assertCountEqual)(*args, **kwargs)695696697def assertRaisesRegex(self, *args, **kwargs):698return getattr(self, _assertRaisesRegex)(*args, **kwargs)699700701def assertRegex(self, *args, **kwargs):702return getattr(self, _assertRegex)(*args, **kwargs)703704705def assertNotRegex(self, *args, **kwargs):706return getattr(self, _assertNotRegex)(*args, **kwargs)707708709if PY3:710exec_ = getattr(moves.builtins, "exec")711712def reraise(tp, value, tb=None):713try:714if value is None:715value = tp()716if value.__traceback__ is not tb:717raise value.with_traceback(tb)718raise value719finally:720value = None721tb = None722723else:724def exec_(_code_, _globs_=None, _locs_=None):725"""Execute code in a namespace."""726if _globs_ is None:727frame = sys._getframe(1)728_globs_ = frame.f_globals729if _locs_ is None:730_locs_ = frame.f_locals731del frame732elif _locs_ is None:733_locs_ = _globs_734exec("""exec _code_ in _globs_, _locs_""")735736exec_("""def reraise(tp, value, tb=None):737try:738raise tp, value, tb739finally:740tb = None741""")742743744if sys.version_info[:2] > (3,):745exec_("""def raise_from(value, from_value):746try:747raise value from from_value748finally:749value = None750""")751else:752def raise_from(value, from_value):753raise value754755756print_ = getattr(moves.builtins, "print", None)757if print_ is None:758def print_(*args, **kwargs):759"""The new-style print function for Python 2.4 and 2.5."""760fp = kwargs.pop("file", sys.stdout)761if fp is None:762return763764def write(data):765if not isinstance(data, basestring):766data = str(data)767# If the file has an encoding, encode unicode with it.768if (isinstance(fp, file) and769isinstance(data, unicode) and770fp.encoding is not None):771errors = getattr(fp, "errors", None)772if errors is None:773errors = "strict"774data = data.encode(fp.encoding, errors)775fp.write(data)776want_unicode = False777sep = kwargs.pop("sep", None)778if sep is not None:779if isinstance(sep, unicode):780want_unicode = True781elif not isinstance(sep, str):782raise TypeError("sep must be None or a string")783end = kwargs.pop("end", None)784if end is not None:785if isinstance(end, unicode):786want_unicode = True787elif not isinstance(end, str):788raise TypeError("end must be None or a string")789if kwargs:790raise TypeError("invalid keyword arguments to print()")791if not want_unicode:792for arg in args:793if isinstance(arg, unicode):794want_unicode = True795break796if want_unicode:797newline = unicode("\n")798space = unicode(" ")799else:800newline = "\n"801space = " "802if sep is None:803sep = space804if end is None:805end = newline806for i, arg in enumerate(args):807if i:808write(sep)809write(arg)810write(end)811if sys.version_info[:2] < (3, 3):812_print = print_813814def print_(*args, **kwargs):815fp = kwargs.get("file", sys.stdout)816flush = kwargs.pop("flush", False)817_print(*args, **kwargs)818if flush and fp is not None:819fp.flush()820821_add_doc(reraise, """Reraise an exception.""")822823if sys.version_info[0:2] < (3, 4):824# This does exactly the same what the :func:`py3:functools.update_wrapper`825# function does on Python versions after 3.2. It sets the ``__wrapped__``826# attribute on ``wrapper`` object and it doesn't raise an error if any of827# the attributes mentioned in ``assigned`` and ``updated`` are missing on828# ``wrapped`` object.829def _update_wrapper(wrapper, wrapped,830assigned=functools.WRAPPER_ASSIGNMENTS,831updated=functools.WRAPPER_UPDATES):832for attr in assigned:833try:834value = getattr(wrapped, attr)835except AttributeError:836continue837else:838setattr(wrapper, attr, value)839for attr in updated:840getattr(wrapper, attr).update(getattr(wrapped, attr, {}))841wrapper.__wrapped__ = wrapped842return wrapper843_update_wrapper.__doc__ = functools.update_wrapper.__doc__844845def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,846updated=functools.WRAPPER_UPDATES):847return functools.partial(_update_wrapper, wrapped=wrapped,848assigned=assigned, updated=updated)849wraps.__doc__ = functools.wraps.__doc__850851else:852wraps = functools.wraps853854855def with_metaclass(meta, *bases):856"""Create a base class with a metaclass."""857# This requires a bit of explanation: the basic idea is to make a dummy858# metaclass for one level of class instantiation that replaces itself with859# the actual metaclass.860class metaclass(type):861862def __new__(cls, name, this_bases, d):863if sys.version_info[:2] >= (3, 7):864# This version introduced PEP 560 that requires a bit865# of extra care (we mimic what is done by __build_class__).866resolved_bases = types.resolve_bases(bases)867if resolved_bases is not bases:868d['__orig_bases__'] = bases869else:870resolved_bases = bases871return meta(name, resolved_bases, d)872873@classmethod874def __prepare__(cls, name, this_bases):875return meta.__prepare__(name, bases)876return type.__new__(metaclass, 'temporary_class', (), {})877878879def add_metaclass(metaclass):880"""Class decorator for creating a class with a metaclass."""881def wrapper(cls):882orig_vars = cls.__dict__.copy()883slots = orig_vars.get('__slots__')884if slots is not None:885if isinstance(slots, str):886slots = [slots]887for slots_var in slots:888orig_vars.pop(slots_var)889orig_vars.pop('__dict__', None)890orig_vars.pop('__weakref__', None)891if hasattr(cls, '__qualname__'):892orig_vars['__qualname__'] = cls.__qualname__893return metaclass(cls.__name__, cls.__bases__, orig_vars)894return wrapper895896897def ensure_binary(s, encoding='utf-8', errors='strict'):898"""Coerce **s** to six.binary_type.899900For Python 2:901- `unicode` -> encoded to `str`902- `str` -> `str`903904For Python 3:905- `str` -> encoded to `bytes`906- `bytes` -> `bytes`907"""908if isinstance(s, binary_type):909return s910if isinstance(s, text_type):911return s.encode(encoding, errors)912raise TypeError("not expecting type '%s'" % type(s))913914915def ensure_str(s, encoding='utf-8', errors='strict'):916"""Coerce *s* to `str`.917918For Python 2:919- `unicode` -> encoded to `str`920- `str` -> `str`921922For Python 3:923- `str` -> `str`924- `bytes` -> decoded to `str`925"""926# Optimization: Fast return for the common case.927if type(s) is str:928return s929if PY2 and isinstance(s, text_type):930return s.encode(encoding, errors)931elif PY3 and isinstance(s, binary_type):932return s.decode(encoding, errors)933elif not isinstance(s, (text_type, binary_type)):934raise TypeError("not expecting type '%s'" % type(s))935return s936937938def ensure_text(s, encoding='utf-8', errors='strict'):939"""Coerce *s* to six.text_type.940941For Python 2:942- `unicode` -> `unicode`943- `str` -> `unicode`944945For Python 3:946- `str` -> `str`947- `bytes` -> decoded to `str`948"""949if isinstance(s, binary_type):950return s.decode(encoding, errors)951elif isinstance(s, text_type):952return s953else:954raise TypeError("not expecting type '%s'" % type(s))955956957def python_2_unicode_compatible(klass):958"""959A class decorator that defines __unicode__ and __str__ methods under Python 2.960Under Python 3 it does nothing.961962To support Python 2 and 3 with a single code base, define a __str__ method963returning text and apply this decorator to the class.964"""965if PY2:966if '__str__' not in klass.__dict__:967raise ValueError("@python_2_unicode_compatible cannot be applied "968"to %s because it doesn't define __str__()." %969klass.__name__)970klass.__unicode__ = klass.__str__971klass.__str__ = lambda self: self.__unicode__().encode('utf-8')972return klass973974975# Complete the moves implementation.976# This code is at the end of this module to speed up module loading.977# Turn this module into a package.978__path__ = [] # required for PEP 302 and PEP 451979__package__ = __name__ # see PEP 366 @ReservedAssignment980if globals().get("__spec__") is not None:981__spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable982# Remove other six meta path importers, since they cause problems. This can983# happen if six is removed from sys.modules and then reloaded. (Setuptools does984# this for some reason.)985if sys.meta_path:986for i, importer in enumerate(sys.meta_path):987# Here's some real nastiness: Another "instance" of the six module might988# be floating around. Therefore, we can't use isinstance() to check for989# the six meta path importer, since the other six instance will have990# inserted an importer with different class.991if (type(importer).__name__ == "_SixMetaPathImporter" and992importer.name == __name__):993del sys.meta_path[i]994break995del i, importer996# Finally, add the importer to the meta path import hook.997sys.meta_path.append(_importer)9989991000