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