|
| 1 | +""" |
| 2 | +To ensure compatibility from Python ``2.6`` - ``3.3``, a module has been |
| 3 | +created. Clearly there is huge need to use conforming syntax. |
| 4 | +""" |
| 5 | +import sys |
| 6 | +import imp |
| 7 | +import os |
| 8 | +import re |
| 9 | +try: |
| 10 | + import importlib |
| 11 | +except ImportError: |
| 12 | + pass |
| 13 | + |
| 14 | +is_py3 = sys.version_info[0] >= 3 |
| 15 | +is_py33 = is_py3 and sys.version_info.minor >= 3 |
| 16 | +is_py26 = not is_py3 and sys.version_info[1] < 7 |
| 17 | + |
| 18 | + |
| 19 | +def find_module_py33(string, path=None): |
| 20 | + loader = importlib.machinery.PathFinder.find_module(string, path) |
| 21 | + |
| 22 | + if loader is None and path is None: # Fallback to find builtins |
| 23 | + try: |
| 24 | + loader = importlib.find_loader(string) |
| 25 | + except ValueError as e: |
| 26 | + # See #491. Importlib might raise a ValueError, to avoid this, we |
| 27 | + # just raise an ImportError to fix the issue. |
| 28 | + raise ImportError("Originally ValueError: " + e.message) |
| 29 | + |
| 30 | + if loader is None: |
| 31 | + raise ImportError("Couldn't find a loader for {0}".format(string)) |
| 32 | + |
| 33 | + try: |
| 34 | + is_package = loader.is_package(string) |
| 35 | + if is_package: |
| 36 | + module_path = os.path.dirname(loader.path) |
| 37 | + module_file = None |
| 38 | + else: |
| 39 | + module_path = loader.get_filename(string) |
| 40 | + module_file = open(module_path, 'rb') |
| 41 | + except AttributeError: |
| 42 | + # ExtensionLoader has not attribute get_filename, instead it has a |
| 43 | + # path attribute that we can use to retrieve the module path |
| 44 | + try: |
| 45 | + module_path = loader.path |
| 46 | + module_file = open(loader.path, 'rb') |
| 47 | + except AttributeError: |
| 48 | + module_path = string |
| 49 | + module_file = None |
| 50 | + finally: |
| 51 | + is_package = False |
| 52 | + |
| 53 | + return module_file, module_path, is_package |
| 54 | + |
| 55 | + |
| 56 | +def find_module_pre_py33(string, path=None): |
| 57 | + module_file, module_path, description = imp.find_module(string, path) |
| 58 | + module_type = description[2] |
| 59 | + return module_file, module_path, module_type is imp.PKG_DIRECTORY |
| 60 | + |
| 61 | + |
| 62 | +find_module = find_module_py33 if is_py33 else find_module_pre_py33 |
| 63 | +find_module.__doc__ = """ |
| 64 | +Provides information about a module. |
| 65 | +
|
| 66 | +This function isolates the differences in importing libraries introduced with |
| 67 | +python 3.3 on; it gets a module name and optionally a path. It will return a |
| 68 | +tuple containin an open file for the module (if not builtin), the filename |
| 69 | +or the name of the module if it is a builtin one and a boolean indicating |
| 70 | +if the module is contained in a package. |
| 71 | +""" |
| 72 | + |
| 73 | + |
| 74 | +# unicode function |
| 75 | +try: |
| 76 | + unicode = unicode |
| 77 | +except NameError: |
| 78 | + unicode = str |
| 79 | + |
| 80 | +if is_py3: |
| 81 | + u = lambda s: s |
| 82 | +else: |
| 83 | + u = lambda s: s.decode('utf-8') |
| 84 | + |
| 85 | +u.__doc__ = """ |
| 86 | +Decode a raw string into unicode object. Do nothing in Python 3. |
| 87 | +""" |
| 88 | + |
| 89 | +# exec function |
| 90 | +if is_py3: |
| 91 | + def exec_function(source, global_map): |
| 92 | + exec(source, global_map) |
| 93 | +else: |
| 94 | + eval(compile("""def exec_function(source, global_map): |
| 95 | + exec source in global_map """, 'blub', 'exec')) |
| 96 | + |
| 97 | +# re-raise function |
| 98 | +if is_py3: |
| 99 | + def reraise(exception, traceback): |
| 100 | + raise exception.with_traceback(traceback) |
| 101 | +else: |
| 102 | + eval(compile(""" |
| 103 | +def reraise(exception, traceback): |
| 104 | + raise exception, None, traceback |
| 105 | +""", 'blub', 'exec')) |
| 106 | + |
| 107 | +reraise.__doc__ = """ |
| 108 | +Re-raise `exception` with a `traceback` object. |
| 109 | +
|
| 110 | +Usage:: |
| 111 | +
|
| 112 | + reraise(Exception, sys.exc_info()[2]) |
| 113 | +
|
| 114 | +""" |
| 115 | + |
| 116 | +class Python3Method(object): |
| 117 | + def __init__(self, func): |
| 118 | + self.func = func |
| 119 | + |
| 120 | + def __get__(self, obj, objtype): |
| 121 | + if obj is None: |
| 122 | + return lambda *args, **kwargs: self.func(*args, **kwargs) |
| 123 | + else: |
| 124 | + return lambda *args, **kwargs: self.func(obj, *args, **kwargs) |
| 125 | + |
| 126 | + |
| 127 | +def use_metaclass(meta, *bases): |
| 128 | + """ Create a class with a metaclass. """ |
| 129 | + if not bases: |
| 130 | + bases = (object,) |
| 131 | + return meta("HackClass", bases, {}) |
| 132 | + |
| 133 | + |
| 134 | +try: |
| 135 | + encoding = sys.stdout.encoding |
| 136 | + if encoding is None: |
| 137 | + encoding = 'utf-8' |
| 138 | +except AttributeError: |
| 139 | + encoding = 'ascii' |
| 140 | + |
| 141 | + |
| 142 | +def u(string): |
| 143 | + """Cast to unicode DAMMIT! |
| 144 | + Written because Python2 repr always implicitly casts to a string, so we |
| 145 | + have to cast back to a unicode (and we now that we always deal with valid |
| 146 | + unicode, because we check that in the beginning). |
| 147 | + """ |
| 148 | + if is_py3: |
| 149 | + return str(string) |
| 150 | + elif not isinstance(string, unicode): |
| 151 | + return unicode(str(string), 'UTF-8') |
| 152 | + return string |
| 153 | + |
| 154 | +try: |
| 155 | + import builtins # module name in python 3 |
| 156 | +except ImportError: |
| 157 | + import __builtin__ as builtins |
| 158 | + |
| 159 | + |
| 160 | +import ast |
| 161 | + |
| 162 | + |
| 163 | +def literal_eval(string): |
| 164 | + # py3.0, py3.1 and py32 don't support unicode literals. Support those, I |
| 165 | + # don't want to write two versions of the tokenizer. |
| 166 | + if is_py3 and sys.version_info.minor < 3: |
| 167 | + if re.match('[uU][\'"]', string): |
| 168 | + string = string[1:] |
| 169 | + return ast.literal_eval(string) |
| 170 | + |
| 171 | + |
| 172 | +try: |
| 173 | + from itertools import zip_longest |
| 174 | +except ImportError: |
| 175 | + from itertools import izip_longest as zip_longest # Python 2 |
| 176 | + |
| 177 | + |
| 178 | +def no_unicode_pprint(dct): |
| 179 | + """ |
| 180 | + Python 2/3 dict __repr__ may be different, because of unicode differens |
| 181 | + (with or without a `u` prefix). Normally in doctests we could use `pprint` |
| 182 | + to sort dicts and check for equality, but here we have to write a separate |
| 183 | + function to do that. |
| 184 | + """ |
| 185 | + import pprint |
| 186 | + s = pprint.pformat(dct) |
| 187 | + print(re.sub("u'", "'", s)) |
| 188 | + |
| 189 | + |
| 190 | +def utf8_repr(func): |
| 191 | + """ |
| 192 | + ``__repr__`` methods in Python 2 don't allow unicode objects to be |
| 193 | + returned. Therefore cast them to utf-8 bytes in this decorator. |
| 194 | + """ |
| 195 | + def wrapper(self): |
| 196 | + result = func(self) |
| 197 | + if isinstance(result, unicode): |
| 198 | + return result.encode('utf-8') |
| 199 | + else: |
| 200 | + return result |
| 201 | + |
| 202 | + if is_py3: |
| 203 | + return func |
| 204 | + else: |
| 205 | + return wrapper |
0 commit comments