1import sys
2
3
4# Passthrough for builtins supported with py27.
5BaseException = BaseException
6GeneratorExit = GeneratorExit
7_sysex = (KeyboardInterrupt, SystemExit, MemoryError, GeneratorExit)
8all = all
9any = any
10callable = callable
11enumerate = enumerate
12reversed = reversed
13set, frozenset = set, frozenset
14sorted = sorted
15
16
17if sys.version_info >= (3, 0):
18    exec("print_ = print ; exec_=exec")
19    import builtins
20
21    # some backward compatibility helpers
22    _basestring = str
23    def _totext(obj, encoding=None, errors=None):
24        if isinstance(obj, bytes):
25            if errors is None:
26                obj = obj.decode(encoding)
27            else:
28                obj = obj.decode(encoding, errors)
29        elif not isinstance(obj, str):
30            obj = str(obj)
31        return obj
32
33    def _isbytes(x):
34        return isinstance(x, bytes)
35
36    def _istext(x):
37        return isinstance(x, str)
38
39    text = str
40    bytes = bytes
41
42    def _getimself(function):
43        return getattr(function, '__self__', None)
44
45    def _getfuncdict(function):
46        return getattr(function, "__dict__", None)
47
48    def _getcode(function):
49        return getattr(function, "__code__", None)
50
51    def execfile(fn, globs=None, locs=None):
52        if globs is None:
53            back = sys._getframe(1)
54            globs = back.f_globals
55            locs = back.f_locals
56            del back
57        elif locs is None:
58            locs = globs
59        fp = open(fn, "r")
60        try:
61            source = fp.read()
62        finally:
63            fp.close()
64        co = compile(source, fn, "exec", dont_inherit=True)
65        exec_(co, globs, locs)
66
67else:
68    import __builtin__ as builtins
69    _totext = unicode
70    _basestring = basestring
71    text = unicode
72    bytes = str
73    execfile = execfile
74    callable = callable
75    def _isbytes(x):
76        return isinstance(x, str)
77    def _istext(x):
78        return isinstance(x, unicode)
79
80    def _getimself(function):
81        return getattr(function, 'im_self', None)
82
83    def _getfuncdict(function):
84        return getattr(function, "__dict__", None)
85
86    def _getcode(function):
87        try:
88            return getattr(function, "__code__")
89        except AttributeError:
90            return getattr(function, "func_code", None)
91
92    def print_(*args, **kwargs):
93        """ minimal backport of py3k print statement. """
94        sep = ' '
95        if 'sep' in kwargs:
96            sep = kwargs.pop('sep')
97        end = '\n'
98        if 'end' in kwargs:
99            end = kwargs.pop('end')
100        file = 'file' in kwargs and kwargs.pop('file') or sys.stdout
101        if kwargs:
102            args = ", ".join([str(x) for x in kwargs])
103            raise TypeError("invalid keyword arguments: %s" % args)
104        at_start = True
105        for x in args:
106            if not at_start:
107                file.write(sep)
108            file.write(str(x))
109            at_start = False
110        file.write(end)
111
112    def exec_(obj, globals=None, locals=None):
113        """ minimal backport of py3k exec statement. """
114        __tracebackhide__ = True
115        if globals is None:
116            frame = sys._getframe(1)
117            globals = frame.f_globals
118            if locals is None:
119                locals = frame.f_locals
120        elif locals is None:
121            locals = globals
122        exec2(obj, globals, locals)
123
124if sys.version_info >= (3, 0):
125    def _reraise(cls, val, tb):
126        __tracebackhide__ = True
127        assert hasattr(val, '__traceback__')
128        raise cls.with_traceback(val, tb)
129else:
130    exec ("""
131def _reraise(cls, val, tb):
132    __tracebackhide__ = True
133    raise cls, val, tb
134def exec2(obj, globals, locals):
135    __tracebackhide__ = True
136    exec obj in globals, locals
137""")
138
139def _tryimport(*names):
140    """ return the first successfully imported module. """
141    assert names
142    for name in names:
143        try:
144            __import__(name)
145        except ImportError:
146            excinfo = sys.exc_info()
147        else:
148            return sys.modules[name]
149    _reraise(*excinfo)
150