Path: blob/master/venv/Lib/site-packages/setuptools/_vendor/six.py
811 views
"""Utilities for writing code that runs on Python 2 and 3"""12# Copyright (c) 2010-2015 Benjamin Peterson3#4# Permission is hereby granted, free of charge, to any person obtaining a copy5# of this software and associated documentation files (the "Software"), to deal6# in the Software without restriction, including without limitation the rights7# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell8# copies of the Software, and to permit persons to whom the Software is9# furnished to do so, subject to the following conditions:10#11# The above copyright notice and this permission notice shall be included in all12# copies or substantial portions of the Software.13#14# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE17# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,19# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE20# SOFTWARE.2122from __future__ import absolute_import2324import functools25import itertools26import operator27import sys28import types2930__author__ = "Benjamin Peterson <[email protected]>"31__version__ = "1.10.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("range", "__builtin__", "builtins", "xrange", "range"),244MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"),245MovedAttribute("reduce", "__builtin__", "functools"),246MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),247MovedAttribute("StringIO", "StringIO", "io"),248MovedAttribute("UserDict", "UserDict", "collections"),249MovedAttribute("UserList", "UserList", "collections"),250MovedAttribute("UserString", "UserString", "collections"),251MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),252MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),253MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),254MovedModule("builtins", "__builtin__"),255MovedModule("configparser", "ConfigParser"),256MovedModule("copyreg", "copy_reg"),257MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),258MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"),259MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),260MovedModule("http_cookies", "Cookie", "http.cookies"),261MovedModule("html_entities", "htmlentitydefs", "html.entities"),262MovedModule("html_parser", "HTMLParser", "html.parser"),263MovedModule("http_client", "httplib", "http.client"),264MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),265MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"),266MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),267MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),268MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),269MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),270MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),271MovedModule("cPickle", "cPickle", "pickle"),272MovedModule("queue", "Queue"),273MovedModule("reprlib", "repr"),274MovedModule("socketserver", "SocketServer"),275MovedModule("_thread", "thread", "_thread"),276MovedModule("tkinter", "Tkinter"),277MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),278MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),279MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),280MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),281MovedModule("tkinter_tix", "Tix", "tkinter.tix"),282MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),283MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),284MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),285MovedModule("tkinter_colorchooser", "tkColorChooser",286"tkinter.colorchooser"),287MovedModule("tkinter_commondialog", "tkCommonDialog",288"tkinter.commondialog"),289MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),290MovedModule("tkinter_font", "tkFont", "tkinter.font"),291MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),292MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",293"tkinter.simpledialog"),294MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),295MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),296MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),297MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),298MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),299MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),300]301# Add windows specific modules.302if sys.platform == "win32":303_moved_attributes += [304MovedModule("winreg", "_winreg"),305]306307for attr in _moved_attributes:308setattr(_MovedItems, attr.name, attr)309if isinstance(attr, MovedModule):310_importer._add_module(attr, "moves." + attr.name)311del attr312313_MovedItems._moved_attributes = _moved_attributes314315moves = _MovedItems(__name__ + ".moves")316_importer._add_module(moves, "moves")317318319class Module_six_moves_urllib_parse(_LazyModule):320321"""Lazy loading of moved objects in six.moves.urllib_parse"""322323324_urllib_parse_moved_attributes = [325MovedAttribute("ParseResult", "urlparse", "urllib.parse"),326MovedAttribute("SplitResult", "urlparse", "urllib.parse"),327MovedAttribute("parse_qs", "urlparse", "urllib.parse"),328MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),329MovedAttribute("urldefrag", "urlparse", "urllib.parse"),330MovedAttribute("urljoin", "urlparse", "urllib.parse"),331MovedAttribute("urlparse", "urlparse", "urllib.parse"),332MovedAttribute("urlsplit", "urlparse", "urllib.parse"),333MovedAttribute("urlunparse", "urlparse", "urllib.parse"),334MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),335MovedAttribute("quote", "urllib", "urllib.parse"),336MovedAttribute("quote_plus", "urllib", "urllib.parse"),337MovedAttribute("unquote", "urllib", "urllib.parse"),338MovedAttribute("unquote_plus", "urllib", "urllib.parse"),339MovedAttribute("urlencode", "urllib", "urllib.parse"),340MovedAttribute("splitquery", "urllib", "urllib.parse"),341MovedAttribute("splittag", "urllib", "urllib.parse"),342MovedAttribute("splituser", "urllib", "urllib.parse"),343MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),344MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),345MovedAttribute("uses_params", "urlparse", "urllib.parse"),346MovedAttribute("uses_query", "urlparse", "urllib.parse"),347MovedAttribute("uses_relative", "urlparse", "urllib.parse"),348]349for attr in _urllib_parse_moved_attributes:350setattr(Module_six_moves_urllib_parse, attr.name, attr)351del attr352353Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes354355_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),356"moves.urllib_parse", "moves.urllib.parse")357358359class Module_six_moves_urllib_error(_LazyModule):360361"""Lazy loading of moved objects in six.moves.urllib_error"""362363364_urllib_error_moved_attributes = [365MovedAttribute("URLError", "urllib2", "urllib.error"),366MovedAttribute("HTTPError", "urllib2", "urllib.error"),367MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),368]369for attr in _urllib_error_moved_attributes:370setattr(Module_six_moves_urllib_error, attr.name, attr)371del attr372373Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes374375_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),376"moves.urllib_error", "moves.urllib.error")377378379class Module_six_moves_urllib_request(_LazyModule):380381"""Lazy loading of moved objects in six.moves.urllib_request"""382383384_urllib_request_moved_attributes = [385MovedAttribute("urlopen", "urllib2", "urllib.request"),386MovedAttribute("install_opener", "urllib2", "urllib.request"),387MovedAttribute("build_opener", "urllib2", "urllib.request"),388MovedAttribute("pathname2url", "urllib", "urllib.request"),389MovedAttribute("url2pathname", "urllib", "urllib.request"),390MovedAttribute("getproxies", "urllib", "urllib.request"),391MovedAttribute("Request", "urllib2", "urllib.request"),392MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),393MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),394MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),395MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),396MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),397MovedAttribute("BaseHandler", "urllib2", "urllib.request"),398MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),399MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),400MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),401MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),402MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),403MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),404MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),405MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),406MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),407MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),408MovedAttribute("FileHandler", "urllib2", "urllib.request"),409MovedAttribute("FTPHandler", "urllib2", "urllib.request"),410MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),411MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),412MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),413MovedAttribute("urlretrieve", "urllib", "urllib.request"),414MovedAttribute("urlcleanup", "urllib", "urllib.request"),415MovedAttribute("URLopener", "urllib", "urllib.request"),416MovedAttribute("FancyURLopener", "urllib", "urllib.request"),417MovedAttribute("proxy_bypass", "urllib", "urllib.request"),418]419for attr in _urllib_request_moved_attributes:420setattr(Module_six_moves_urllib_request, attr.name, attr)421del attr422423Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes424425_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),426"moves.urllib_request", "moves.urllib.request")427428429class Module_six_moves_urllib_response(_LazyModule):430431"""Lazy loading of moved objects in six.moves.urllib_response"""432433434_urllib_response_moved_attributes = [435MovedAttribute("addbase", "urllib", "urllib.response"),436MovedAttribute("addclosehook", "urllib", "urllib.response"),437MovedAttribute("addinfo", "urllib", "urllib.response"),438MovedAttribute("addinfourl", "urllib", "urllib.response"),439]440for attr in _urllib_response_moved_attributes:441setattr(Module_six_moves_urllib_response, attr.name, attr)442del attr443444Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes445446_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),447"moves.urllib_response", "moves.urllib.response")448449450class Module_six_moves_urllib_robotparser(_LazyModule):451452"""Lazy loading of moved objects in six.moves.urllib_robotparser"""453454455_urllib_robotparser_moved_attributes = [456MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),457]458for attr in _urllib_robotparser_moved_attributes:459setattr(Module_six_moves_urllib_robotparser, attr.name, attr)460del attr461462Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes463464_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),465"moves.urllib_robotparser", "moves.urllib.robotparser")466467468class Module_six_moves_urllib(types.ModuleType):469470"""Create a six.moves.urllib namespace that resembles the Python 3 namespace"""471__path__ = [] # mark as package472parse = _importer._get_module("moves.urllib_parse")473error = _importer._get_module("moves.urllib_error")474request = _importer._get_module("moves.urllib_request")475response = _importer._get_module("moves.urllib_response")476robotparser = _importer._get_module("moves.urllib_robotparser")477478def __dir__(self):479return ['parse', 'error', 'request', 'response', 'robotparser']480481_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),482"moves.urllib")483484485def add_move(move):486"""Add an item to six.moves."""487setattr(_MovedItems, move.name, move)488489490def remove_move(name):491"""Remove item from six.moves."""492try:493delattr(_MovedItems, name)494except AttributeError:495try:496del moves.__dict__[name]497except KeyError:498raise AttributeError("no such move, %r" % (name,))499500501if PY3:502_meth_func = "__func__"503_meth_self = "__self__"504505_func_closure = "__closure__"506_func_code = "__code__"507_func_defaults = "__defaults__"508_func_globals = "__globals__"509else:510_meth_func = "im_func"511_meth_self = "im_self"512513_func_closure = "func_closure"514_func_code = "func_code"515_func_defaults = "func_defaults"516_func_globals = "func_globals"517518519try:520advance_iterator = next521except NameError:522def advance_iterator(it):523return it.next()524next = advance_iterator525526527try:528callable = callable529except NameError:530def callable(obj):531return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)532533534if PY3:535def get_unbound_function(unbound):536return unbound537538create_bound_method = types.MethodType539540def create_unbound_method(func, cls):541return func542543Iterator = object544else:545def get_unbound_function(unbound):546return unbound.im_func547548def create_bound_method(func, obj):549return types.MethodType(func, obj, obj.__class__)550551def create_unbound_method(func, cls):552return types.MethodType(func, None, cls)553554class Iterator(object):555556def next(self):557return type(self).__next__(self)558559callable = callable560_add_doc(get_unbound_function,561"""Get the function out of a possibly unbound function""")562563564get_method_function = operator.attrgetter(_meth_func)565get_method_self = operator.attrgetter(_meth_self)566get_function_closure = operator.attrgetter(_func_closure)567get_function_code = operator.attrgetter(_func_code)568get_function_defaults = operator.attrgetter(_func_defaults)569get_function_globals = operator.attrgetter(_func_globals)570571572if PY3:573def iterkeys(d, **kw):574return iter(d.keys(**kw))575576def itervalues(d, **kw):577return iter(d.values(**kw))578579def iteritems(d, **kw):580return iter(d.items(**kw))581582def iterlists(d, **kw):583return iter(d.lists(**kw))584585viewkeys = operator.methodcaller("keys")586587viewvalues = operator.methodcaller("values")588589viewitems = operator.methodcaller("items")590else:591def iterkeys(d, **kw):592return d.iterkeys(**kw)593594def itervalues(d, **kw):595return d.itervalues(**kw)596597def iteritems(d, **kw):598return d.iteritems(**kw)599600def iterlists(d, **kw):601return d.iterlists(**kw)602603viewkeys = operator.methodcaller("viewkeys")604605viewvalues = operator.methodcaller("viewvalues")606607viewitems = operator.methodcaller("viewitems")608609_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")610_add_doc(itervalues, "Return an iterator over the values of a dictionary.")611_add_doc(iteritems,612"Return an iterator over the (key, value) pairs of a dictionary.")613_add_doc(iterlists,614"Return an iterator over the (key, [values]) pairs of a dictionary.")615616617if PY3:618def b(s):619return s.encode("latin-1")620621def u(s):622return s623unichr = chr624import struct625int2byte = struct.Struct(">B").pack626del struct627byte2int = operator.itemgetter(0)628indexbytes = operator.getitem629iterbytes = iter630import io631StringIO = io.StringIO632BytesIO = io.BytesIO633_assertCountEqual = "assertCountEqual"634if sys.version_info[1] <= 1:635_assertRaisesRegex = "assertRaisesRegexp"636_assertRegex = "assertRegexpMatches"637else:638_assertRaisesRegex = "assertRaisesRegex"639_assertRegex = "assertRegex"640else:641def b(s):642return s643# Workaround for standalone backslash644645def u(s):646return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")647unichr = unichr648int2byte = chr649650def byte2int(bs):651return ord(bs[0])652653def indexbytes(buf, i):654return ord(buf[i])655iterbytes = functools.partial(itertools.imap, ord)656import StringIO657StringIO = BytesIO = StringIO.StringIO658_assertCountEqual = "assertItemsEqual"659_assertRaisesRegex = "assertRaisesRegexp"660_assertRegex = "assertRegexpMatches"661_add_doc(b, """Byte literal""")662_add_doc(u, """Text literal""")663664665def assertCountEqual(self, *args, **kwargs):666return getattr(self, _assertCountEqual)(*args, **kwargs)667668669def assertRaisesRegex(self, *args, **kwargs):670return getattr(self, _assertRaisesRegex)(*args, **kwargs)671672673def assertRegex(self, *args, **kwargs):674return getattr(self, _assertRegex)(*args, **kwargs)675676677if PY3:678exec_ = getattr(moves.builtins, "exec")679680def reraise(tp, value, tb=None):681if value is None:682value = tp()683if value.__traceback__ is not tb:684raise value.with_traceback(tb)685raise value686687else:688def exec_(_code_, _globs_=None, _locs_=None):689"""Execute code in a namespace."""690if _globs_ is None:691frame = sys._getframe(1)692_globs_ = frame.f_globals693if _locs_ is None:694_locs_ = frame.f_locals695del frame696elif _locs_ is None:697_locs_ = _globs_698exec("""exec _code_ in _globs_, _locs_""")699700exec_("""def reraise(tp, value, tb=None):701raise tp, value, tb702""")703704705if sys.version_info[:2] == (3, 2):706exec_("""def raise_from(value, from_value):707if from_value is None:708raise value709raise value from from_value710""")711elif sys.version_info[:2] > (3, 2):712exec_("""def raise_from(value, from_value):713raise value from from_value714""")715else:716def raise_from(value, from_value):717raise value718719720print_ = getattr(moves.builtins, "print", None)721if print_ is None:722def print_(*args, **kwargs):723"""The new-style print function for Python 2.4 and 2.5."""724fp = kwargs.pop("file", sys.stdout)725if fp is None:726return727728def write(data):729if not isinstance(data, basestring):730data = str(data)731# If the file has an encoding, encode unicode with it.732if (isinstance(fp, file) and733isinstance(data, unicode) and734fp.encoding is not None):735errors = getattr(fp, "errors", None)736if errors is None:737errors = "strict"738data = data.encode(fp.encoding, errors)739fp.write(data)740want_unicode = False741sep = kwargs.pop("sep", None)742if sep is not None:743if isinstance(sep, unicode):744want_unicode = True745elif not isinstance(sep, str):746raise TypeError("sep must be None or a string")747end = kwargs.pop("end", None)748if end is not None:749if isinstance(end, unicode):750want_unicode = True751elif not isinstance(end, str):752raise TypeError("end must be None or a string")753if kwargs:754raise TypeError("invalid keyword arguments to print()")755if not want_unicode:756for arg in args:757if isinstance(arg, unicode):758want_unicode = True759break760if want_unicode:761newline = unicode("\n")762space = unicode(" ")763else:764newline = "\n"765space = " "766if sep is None:767sep = space768if end is None:769end = newline770for i, arg in enumerate(args):771if i:772write(sep)773write(arg)774write(end)775if sys.version_info[:2] < (3, 3):776_print = print_777778def print_(*args, **kwargs):779fp = kwargs.get("file", sys.stdout)780flush = kwargs.pop("flush", False)781_print(*args, **kwargs)782if flush and fp is not None:783fp.flush()784785_add_doc(reraise, """Reraise an exception.""")786787if sys.version_info[0:2] < (3, 4):788def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,789updated=functools.WRAPPER_UPDATES):790def wrapper(f):791f = functools.wraps(wrapped, assigned, updated)(f)792f.__wrapped__ = wrapped793return f794return wrapper795else:796wraps = functools.wraps797798799def with_metaclass(meta, *bases):800"""Create a base class with a metaclass."""801# This requires a bit of explanation: the basic idea is to make a dummy802# metaclass for one level of class instantiation that replaces itself with803# the actual metaclass.804class metaclass(meta):805806def __new__(cls, name, this_bases, d):807return meta(name, bases, d)808return type.__new__(metaclass, 'temporary_class', (), {})809810811def add_metaclass(metaclass):812"""Class decorator for creating a class with a metaclass."""813def wrapper(cls):814orig_vars = cls.__dict__.copy()815slots = orig_vars.get('__slots__')816if slots is not None:817if isinstance(slots, str):818slots = [slots]819for slots_var in slots:820orig_vars.pop(slots_var)821orig_vars.pop('__dict__', None)822orig_vars.pop('__weakref__', None)823return metaclass(cls.__name__, cls.__bases__, orig_vars)824return wrapper825826827def python_2_unicode_compatible(klass):828"""829A decorator that defines __unicode__ and __str__ methods under Python 2.830Under Python 3 it does nothing.831832To support Python 2 and 3 with a single code base, define a __str__ method833returning text and apply this decorator to the class.834"""835if PY2:836if '__str__' not in klass.__dict__:837raise ValueError("@python_2_unicode_compatible cannot be applied "838"to %s because it doesn't define __str__()." %839klass.__name__)840klass.__unicode__ = klass.__str__841klass.__str__ = lambda self: self.__unicode__().encode('utf-8')842return klass843844845# Complete the moves implementation.846# This code is at the end of this module to speed up module loading.847# Turn this module into a package.848__path__ = [] # required for PEP 302 and PEP 451849__package__ = __name__ # see PEP 366 @ReservedAssignment850if globals().get("__spec__") is not None:851__spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable852# Remove other six meta path importers, since they cause problems. This can853# happen if six is removed from sys.modules and then reloaded. (Setuptools does854# this for some reason.)855if sys.meta_path:856for i, importer in enumerate(sys.meta_path):857# Here's some real nastiness: Another "instance" of the six module might858# be floating around. Therefore, we can't use isinstance() to check for859# the six meta path importer, since the other six instance will have860# inserted an importer with different class.861if (type(importer).__name__ == "_SixMetaPathImporter" and862importer.name == __name__):863del sys.meta_path[i]864break865del i, importer866# Finally, add the importer to the meta path import hook.867sys.meta_path.append(_importer)868869870