Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1 | """This module provides the components needed to build your own __import__ |
| 2 | function. Undocumented functions are obsolete. |
| 3 | |
| 4 | In most cases it is preferred you consider using the importlib module's |
| 5 | functionality over this module. |
| 6 | |
| 7 | """ |
| 8 | # (Probably) need to stay in _imp |
Brett Cannon | 62228db | 2012-04-29 14:38:11 -0400 | [diff] [blame] | 9 | from _imp import (lock_held, acquire_lock, release_lock, |
Brett Cannon | 2fef4d2 | 2012-04-15 19:06:23 -0400 | [diff] [blame] | 10 | load_dynamic, get_frozen_object, is_frozen_package, |
| 11 | init_builtin, init_frozen, is_builtin, is_frozen, |
Brett Cannon | 2657df4 | 2012-05-04 15:20:40 -0400 | [diff] [blame] | 12 | _fix_co_filename, extension_suffixes) |
Brett Cannon | 24117a7 | 2012-04-20 18:04:03 -0400 | [diff] [blame] | 13 | # Could move out of _imp, but not worth the code |
Brett Cannon | 2f92389 | 2012-04-21 18:55:51 -0400 | [diff] [blame] | 14 | from _imp import get_magic, get_tag |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 15 | |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 16 | from importlib._bootstrap import new_module |
| 17 | from importlib._bootstrap import cache_from_source |
Brett Cannon | 01a7617 | 2012-04-15 20:25:23 -0400 | [diff] [blame] | 18 | |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 19 | from importlib import _bootstrap |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame^] | 20 | from importlib import machinery |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 21 | import os |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 22 | import sys |
| 23 | import tokenize |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame^] | 24 | import warnings |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 25 | |
| 26 | |
| 27 | # XXX "deprecate" once find_module(), load_module(), and get_suffixes() are |
| 28 | # deprecated. |
| 29 | SEARCH_ERROR = 0 |
| 30 | PY_SOURCE = 1 |
| 31 | PY_COMPILED = 2 |
| 32 | C_EXTENSION = 3 |
| 33 | PY_RESOURCE = 4 |
| 34 | PKG_DIRECTORY = 5 |
| 35 | C_BUILTIN = 6 |
| 36 | PY_FROZEN = 7 |
| 37 | PY_CODERESOURCE = 8 |
| 38 | IMP_HOOK = 9 |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 39 | |
| 40 | |
Brett Cannon | 2657df4 | 2012-05-04 15:20:40 -0400 | [diff] [blame] | 41 | def get_suffixes(): |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame^] | 42 | warnings.warn('imp.get_suffixes() is deprecated; use the constants ' |
| 43 | 'defined on importlib.machinery instead', |
| 44 | DeprecationWarning, 2) |
Brett Cannon | 2657df4 | 2012-05-04 15:20:40 -0400 | [diff] [blame] | 45 | extensions = [(s, 'rb', C_EXTENSION) for s in extension_suffixes()] |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame^] | 46 | source = [(s, 'U', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES] |
| 47 | bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES] |
Brett Cannon | 2657df4 | 2012-05-04 15:20:40 -0400 | [diff] [blame] | 48 | |
| 49 | return extensions + source + bytecode |
| 50 | |
| 51 | |
Brett Cannon | a64faf0 | 2012-04-21 18:52:52 -0400 | [diff] [blame] | 52 | def source_from_cache(path): |
| 53 | """Given the path to a .pyc./.pyo file, return the path to its .py file. |
| 54 | |
| 55 | The .pyc/.pyo file does not need to exist; this simply returns the path to |
| 56 | the .py file calculated to correspond to the .pyc/.pyo file. If path does |
| 57 | not conform to PEP 3147 format, ValueError will be raised. |
| 58 | |
| 59 | """ |
| 60 | head, pycache_filename = os.path.split(path) |
| 61 | head, pycache = os.path.split(head) |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 62 | if pycache != _bootstrap._PYCACHE: |
Brett Cannon | a64faf0 | 2012-04-21 18:52:52 -0400 | [diff] [blame] | 63 | raise ValueError('{} not bottom-level directory in ' |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 64 | '{!r}'.format(_bootstrap._PYCACHE, path)) |
Brett Cannon | a64faf0 | 2012-04-21 18:52:52 -0400 | [diff] [blame] | 65 | if pycache_filename.count('.') != 2: |
| 66 | raise ValueError('expected only 2 dots in ' |
| 67 | '{!r}'.format(pycache_filename)) |
| 68 | base_filename = pycache_filename.partition('.')[0] |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame^] | 69 | return os.path.join(head, base_filename + machinery.SOURCE_SUFFIXES[0]) |
Brett Cannon | a64faf0 | 2012-04-21 18:52:52 -0400 | [diff] [blame] | 70 | |
| 71 | |
Brett Cannon | acf85cd | 2012-04-29 12:50:03 -0400 | [diff] [blame] | 72 | class NullImporter: |
| 73 | |
| 74 | """Null import object.""" |
| 75 | |
| 76 | def __init__(self, path): |
| 77 | if path == '': |
| 78 | raise ImportError('empty pathname', path='') |
| 79 | elif os.path.isdir(path): |
| 80 | raise ImportError('existing directory', path=path) |
| 81 | |
| 82 | def find_module(self, fullname): |
| 83 | """Always returns None.""" |
| 84 | return None |
| 85 | |
| 86 | |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 87 | class _HackedGetData: |
Brett Cannon | 16475ad | 2012-04-16 22:11:25 -0400 | [diff] [blame] | 88 | |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 89 | """Compatibiilty support for 'file' arguments of various load_*() |
| 90 | functions.""" |
Brett Cannon | 16475ad | 2012-04-16 22:11:25 -0400 | [diff] [blame] | 91 | |
| 92 | def __init__(self, fullname, path, file=None): |
| 93 | super().__init__(fullname, path) |
| 94 | self.file = file |
| 95 | |
| 96 | def get_data(self, path): |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 97 | """Gross hack to contort loader to deal w/ load_*()'s bad API.""" |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 98 | if self.file and path == self.path: |
Brett Cannon | 16475ad | 2012-04-16 22:11:25 -0400 | [diff] [blame] | 99 | with self.file: |
| 100 | # Technically should be returning bytes, but |
| 101 | # SourceLoader.get_code() just passed what is returned to |
| 102 | # compile() which can handle str. And converting to bytes would |
| 103 | # require figuring out the encoding to decode to and |
| 104 | # tokenize.detect_encoding() only accepts bytes. |
| 105 | return self.file.read() |
| 106 | else: |
| 107 | return super().get_data(path) |
| 108 | |
| 109 | |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 110 | class _LoadSourceCompatibility(_HackedGetData, _bootstrap.SourceFileLoader): |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 111 | |
| 112 | """Compatibility support for implementing load_source().""" |
| 113 | |
| 114 | |
Brett Cannon | a64faf0 | 2012-04-21 18:52:52 -0400 | [diff] [blame] | 115 | # XXX deprecate after better API exposed in importlib |
Brett Cannon | 16475ad | 2012-04-16 22:11:25 -0400 | [diff] [blame] | 116 | def load_source(name, pathname, file=None): |
| 117 | return _LoadSourceCompatibility(name, pathname, file).load_module(name) |
| 118 | |
| 119 | |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 120 | class _LoadCompiledCompatibility(_HackedGetData, |
Marc-Andre Lemburg | 4fe29c9 | 2012-04-25 02:31:37 +0200 | [diff] [blame] | 121 | _bootstrap.SourcelessFileLoader): |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 122 | |
| 123 | """Compatibility support for implementing load_compiled().""" |
| 124 | |
| 125 | |
Brett Cannon | a64faf0 | 2012-04-21 18:52:52 -0400 | [diff] [blame] | 126 | # XXX deprecate |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 127 | def load_compiled(name, pathname, file=None): |
| 128 | return _LoadCompiledCompatibility(name, pathname, file).load_module(name) |
| 129 | |
| 130 | |
Brett Cannon | a64faf0 | 2012-04-21 18:52:52 -0400 | [diff] [blame] | 131 | # XXX deprecate |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 132 | def load_package(name, path): |
| 133 | if os.path.isdir(path): |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame^] | 134 | extensions = machinery.SOURCE_SUFFIXES[:] + [machinery.BYTECODE_SUFFIXES] |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 135 | for extension in extensions: |
| 136 | path = os.path.join(path, '__init__'+extension) |
| 137 | if os.path.exists(path): |
| 138 | break |
| 139 | else: |
| 140 | raise ValueError('{!r} is not a package'.format(path)) |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 141 | return _bootstrap.SourceFileLoader(name, path).load_module(name) |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 142 | |
Brett Cannon | 01a7617 | 2012-04-15 20:25:23 -0400 | [diff] [blame] | 143 | |
Brett Cannon | a64faf0 | 2012-04-21 18:52:52 -0400 | [diff] [blame] | 144 | # XXX deprecate |
Brett Cannon | 01a7617 | 2012-04-15 20:25:23 -0400 | [diff] [blame] | 145 | def load_module(name, file, filename, details): |
| 146 | """Load a module, given information returned by find_module(). |
| 147 | |
| 148 | The module name must include the full package name, if any. |
| 149 | |
| 150 | """ |
| 151 | suffix, mode, type_ = details |
Brett Cannon | de10bf4 | 2012-04-16 20:44:21 -0400 | [diff] [blame] | 152 | if mode and (not mode.startswith(('r', 'U')) or '+' in mode): |
Brett Cannon | 01a7617 | 2012-04-15 20:25:23 -0400 | [diff] [blame] | 153 | raise ValueError('invalid file open mode {!r}'.format(mode)) |
| 154 | elif file is None and type_ in {PY_SOURCE, PY_COMPILED}: |
| 155 | msg = 'file object required for import (type code {})'.format(type_) |
| 156 | raise ValueError(msg) |
| 157 | elif type_ == PY_SOURCE: |
| 158 | return load_source(name, filename, file) |
| 159 | elif type_ == PY_COMPILED: |
| 160 | return load_compiled(name, filename, file) |
| 161 | elif type_ == PKG_DIRECTORY: |
| 162 | return load_package(name, filename) |
| 163 | elif type_ == C_BUILTIN: |
| 164 | return init_builtin(name) |
| 165 | elif type_ == PY_FROZEN: |
| 166 | return init_frozen(name) |
| 167 | else: |
| 168 | msg = "Don't know how to import {} (type code {}".format(name, type_) |
| 169 | raise ImportError(msg, name=name) |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 170 | |
| 171 | |
| 172 | def find_module(name, path=None): |
| 173 | """Search for a module. |
| 174 | |
| 175 | If path is omitted or None, search for a built-in, frozen or special |
| 176 | module and continue search in sys.path. The module name cannot |
| 177 | contain '.'; to search for a submodule of a package, pass the |
| 178 | submodule name and the package's __path__. |
| 179 | |
| 180 | """ |
| 181 | if not isinstance(name, str): |
| 182 | raise TypeError("'name' must be a str, not {}".format(type(name))) |
| 183 | elif not isinstance(path, (type(None), list)): |
| 184 | # Backwards-compatibility |
| 185 | raise RuntimeError("'list' must be None or a list, " |
| 186 | "not {}".format(type(name))) |
| 187 | |
| 188 | if path is None: |
| 189 | if is_builtin(name): |
| 190 | return None, None, ('', '', C_BUILTIN) |
| 191 | elif is_frozen(name): |
| 192 | return None, None, ('', '', PY_FROZEN) |
| 193 | else: |
| 194 | path = sys.path |
| 195 | |
| 196 | for entry in path: |
| 197 | package_directory = os.path.join(entry, name) |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame^] | 198 | for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]: |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 199 | package_file_name = '__init__' + suffix |
| 200 | file_path = os.path.join(package_directory, package_file_name) |
| 201 | if os.path.isfile(file_path): |
| 202 | return None, package_directory, ('', '', PKG_DIRECTORY) |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame^] | 203 | with warnings.catch_warnings(): |
| 204 | warnings.simplefilter('ignore') |
| 205 | for suffix, mode, type_ in get_suffixes(): |
| 206 | file_name = name + suffix |
| 207 | file_path = os.path.join(entry, file_name) |
| 208 | if os.path.isfile(file_path): |
| 209 | break |
| 210 | else: |
| 211 | continue |
| 212 | break # Break out of outer loop when breaking out of inner loop. |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 213 | else: |
| 214 | raise ImportError('No module name {!r}'.format(name), name=name) |
| 215 | |
| 216 | encoding = None |
| 217 | if mode == 'U': |
| 218 | with open(file_path, 'rb') as file: |
| 219 | encoding = tokenize.detect_encoding(file.readline)[0] |
| 220 | file = open(file_path, mode, encoding=encoding) |
| 221 | return file, file_path, (suffix, mode, type_) |
Brett Cannon | 62228db | 2012-04-29 14:38:11 -0400 | [diff] [blame] | 222 | |
| 223 | |
| 224 | _RELOADING = {} |
| 225 | |
| 226 | def reload(module): |
| 227 | """Reload the module and return it. |
| 228 | |
| 229 | The module must have been successfully imported before. |
| 230 | |
| 231 | """ |
| 232 | if not module or type(module) != type(sys): |
| 233 | raise TypeError("reload() argument must be module") |
| 234 | name = module.__name__ |
| 235 | if name not in sys.modules: |
| 236 | msg = "module {} not in sys.modules" |
| 237 | raise ImportError(msg.format(name), name=name) |
| 238 | if name in _RELOADING: |
| 239 | return _RELOADING[name] |
| 240 | _RELOADING[name] = module |
| 241 | try: |
| 242 | parent_name = name.rpartition('.')[0] |
| 243 | if parent_name and parent_name not in sys.modules: |
| 244 | msg = "parent {!r} not in sys.modules" |
| 245 | raise ImportError(msg.format(parentname), name=parent_name) |
| 246 | return module.__loader__.load_module(name) |
| 247 | finally: |
| 248 | try: |
| 249 | del _RELOADING[name] |
| 250 | except KeyError: |
| 251 | pass |