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