blob: fcfd3d36ee1a8cc574612868d8932e3bf3f23c73 [file] [log] [blame]
Brett Cannon6f44d662012-04-15 16:08:47 -04001"""This module provides the components needed to build your own __import__
2function. Undocumented functions are obsolete.
3
4In most cases it is preferred you consider using the importlib module's
5functionality over this module.
6
7"""
8# (Probably) need to stay in _imp
Brett Cannon62228db2012-04-29 14:38:11 -04009from _imp import (lock_held, acquire_lock, release_lock,
Brett Cannon2fef4d22012-04-15 19:06:23 -040010 load_dynamic, get_frozen_object, is_frozen_package,
11 init_builtin, init_frozen, is_builtin, is_frozen,
Brett Cannon2657df42012-05-04 15:20:40 -040012 _fix_co_filename, extension_suffixes)
Brett Cannon24117a72012-04-20 18:04:03 -040013# Could move out of _imp, but not worth the code
Brett Cannon98979b82012-07-02 15:13:11 -040014from _imp import get_magic
Brett Cannon6f44d662012-04-15 16:08:47 -040015
Brett Cannon17098a52012-05-04 13:52:49 -040016from importlib._bootstrap import new_module
17from importlib._bootstrap import cache_from_source
Brett Cannon01a76172012-04-15 20:25:23 -040018
Brett Cannon2ee61422012-04-15 22:28:28 -040019from importlib import _bootstrap
Brett Cannoncb66eb02012-05-11 12:58:42 -040020from importlib import machinery
Brett Cannon2ee61422012-04-15 22:28:28 -040021import os
Brett Cannone69f0df2012-04-21 21:09:46 -040022import sys
23import tokenize
Brett Cannoncb66eb02012-05-11 12:58:42 -040024import warnings
Brett Cannone69f0df2012-04-21 21:09:46 -040025
26
Brett Cannonc0499522012-05-11 14:48:41 -040027# DEPRECATED
Brett Cannone69f0df2012-04-21 21:09:46 -040028SEARCH_ERROR = 0
29PY_SOURCE = 1
30PY_COMPILED = 2
31C_EXTENSION = 3
32PY_RESOURCE = 4
33PKG_DIRECTORY = 5
34C_BUILTIN = 6
35PY_FROZEN = 7
36PY_CODERESOURCE = 8
37IMP_HOOK = 9
Brett Cannon2ee61422012-04-15 22:28:28 -040038
39
Brett Cannon98979b82012-07-02 15:13:11 -040040def get_tag():
41 """Return the magic tag for .pyc or .pyo files."""
42 return sys.implementation.cache_tag
43
44
Brett Cannon2657df42012-05-04 15:20:40 -040045def get_suffixes():
Brett Cannoncb66eb02012-05-11 12:58:42 -040046 warnings.warn('imp.get_suffixes() is deprecated; use the constants '
47 'defined on importlib.machinery instead',
48 DeprecationWarning, 2)
Brett Cannon2657df42012-05-04 15:20:40 -040049 extensions = [(s, 'rb', C_EXTENSION) for s in extension_suffixes()]
Brett Cannoncb66eb02012-05-11 12:58:42 -040050 source = [(s, 'U', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
51 bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
Brett Cannon2657df42012-05-04 15:20:40 -040052
53 return extensions + source + bytecode
54
55
Brett Cannona64faf02012-04-21 18:52:52 -040056def source_from_cache(path):
57 """Given the path to a .pyc./.pyo file, return the path to its .py file.
58
59 The .pyc/.pyo file does not need to exist; this simply returns the path to
60 the .py file calculated to correspond to the .pyc/.pyo file. If path does
61 not conform to PEP 3147 format, ValueError will be raised.
62
63 """
64 head, pycache_filename = os.path.split(path)
65 head, pycache = os.path.split(head)
Brett Cannon17098a52012-05-04 13:52:49 -040066 if pycache != _bootstrap._PYCACHE:
Brett Cannona64faf02012-04-21 18:52:52 -040067 raise ValueError('{} not bottom-level directory in '
Brett Cannon17098a52012-05-04 13:52:49 -040068 '{!r}'.format(_bootstrap._PYCACHE, path))
Brett Cannona64faf02012-04-21 18:52:52 -040069 if pycache_filename.count('.') != 2:
70 raise ValueError('expected only 2 dots in '
71 '{!r}'.format(pycache_filename))
72 base_filename = pycache_filename.partition('.')[0]
Brett Cannoncb66eb02012-05-11 12:58:42 -040073 return os.path.join(head, base_filename + machinery.SOURCE_SUFFIXES[0])
Brett Cannona64faf02012-04-21 18:52:52 -040074
75
Brett Cannonacf85cd2012-04-29 12:50:03 -040076class NullImporter:
77
78 """Null import object."""
79
80 def __init__(self, path):
81 if path == '':
82 raise ImportError('empty pathname', path='')
83 elif os.path.isdir(path):
84 raise ImportError('existing directory', path=path)
85
86 def find_module(self, fullname):
87 """Always returns None."""
88 return None
89
90
Brett Cannon64befe92012-04-17 19:14:26 -040091class _HackedGetData:
Brett Cannon16475ad2012-04-16 22:11:25 -040092
Brett Cannon64befe92012-04-17 19:14:26 -040093 """Compatibiilty support for 'file' arguments of various load_*()
94 functions."""
Brett Cannon16475ad2012-04-16 22:11:25 -040095
96 def __init__(self, fullname, path, file=None):
97 super().__init__(fullname, path)
98 self.file = file
99
100 def get_data(self, path):
Brett Cannon64befe92012-04-17 19:14:26 -0400101 """Gross hack to contort loader to deal w/ load_*()'s bad API."""
Brett Cannon938d44d2012-04-22 19:58:33 -0400102 if self.file and path == self.path:
Brett Cannon16475ad2012-04-16 22:11:25 -0400103 with self.file:
104 # Technically should be returning bytes, but
105 # SourceLoader.get_code() just passed what is returned to
106 # compile() which can handle str. And converting to bytes would
107 # require figuring out the encoding to decode to and
108 # tokenize.detect_encoding() only accepts bytes.
109 return self.file.read()
110 else:
111 return super().get_data(path)
112
113
Brett Cannon938d44d2012-04-22 19:58:33 -0400114class _LoadSourceCompatibility(_HackedGetData, _bootstrap.SourceFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400115
116 """Compatibility support for implementing load_source()."""
117
118
Brett Cannon16475ad2012-04-16 22:11:25 -0400119def load_source(name, pathname, file=None):
Brett Cannonc0499522012-05-11 14:48:41 -0400120 msg = ('imp.load_source() is deprecated; use '
121 'importlib.machinery.SourceFileLoader(name, pathname).load_module()'
122 ' instead')
123 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon16475ad2012-04-16 22:11:25 -0400124 return _LoadSourceCompatibility(name, pathname, file).load_module(name)
125
126
Brett Cannon64befe92012-04-17 19:14:26 -0400127class _LoadCompiledCompatibility(_HackedGetData,
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200128 _bootstrap.SourcelessFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400129
130 """Compatibility support for implementing load_compiled()."""
131
132
133def load_compiled(name, pathname, file=None):
Brett Cannonc0499522012-05-11 14:48:41 -0400134 msg = ('imp.load_compiled() is deprecated; use '
135 'importlib.machinery.SourcelessFileLoader(name, pathname).'
136 'load_module() instead ')
137 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon64befe92012-04-17 19:14:26 -0400138 return _LoadCompiledCompatibility(name, pathname, file).load_module(name)
139
140
Brett Cannon2ee61422012-04-15 22:28:28 -0400141def load_package(name, path):
Brett Cannonc0499522012-05-11 14:48:41 -0400142 msg = ('imp.load_package() is deprecated; use either '
143 'importlib.machinery.SourceFileLoader() or '
144 'importlib.machinery.SourcelessFileLoader() instead')
145 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon2ee61422012-04-15 22:28:28 -0400146 if os.path.isdir(path):
Brett Cannonc0499522012-05-11 14:48:41 -0400147 extensions = (machinery.SOURCE_SUFFIXES[:] +
148 machinery.BYTECODE_SUFFIXES[:])
Brett Cannon2ee61422012-04-15 22:28:28 -0400149 for extension in extensions:
150 path = os.path.join(path, '__init__'+extension)
151 if os.path.exists(path):
152 break
153 else:
154 raise ValueError('{!r} is not a package'.format(path))
Brett Cannon938d44d2012-04-22 19:58:33 -0400155 return _bootstrap.SourceFileLoader(name, path).load_module(name)
Brett Cannon2ee61422012-04-15 22:28:28 -0400156
Brett Cannon01a76172012-04-15 20:25:23 -0400157
158def load_module(name, file, filename, details):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400159 """**DEPRECATED**
160
161 Load a module, given information returned by find_module().
Brett Cannon01a76172012-04-15 20:25:23 -0400162
163 The module name must include the full package name, if any.
164
165 """
166 suffix, mode, type_ = details
Brett Cannonc0499522012-05-11 14:48:41 -0400167 with warnings.catch_warnings():
168 warnings.simplefilter('ignore')
169 if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
170 raise ValueError('invalid file open mode {!r}'.format(mode))
171 elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
172 msg = 'file object required for import (type code {})'.format(type_)
173 raise ValueError(msg)
174 elif type_ == PY_SOURCE:
175 return load_source(name, filename, file)
176 elif type_ == PY_COMPILED:
177 return load_compiled(name, filename, file)
178 elif type_ == PKG_DIRECTORY:
179 return load_package(name, filename)
180 elif type_ == C_BUILTIN:
181 return init_builtin(name)
182 elif type_ == PY_FROZEN:
183 return init_frozen(name)
184 else:
185 msg = "Don't know how to import {} (type code {}".format(name, type_)
186 raise ImportError(msg, name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400187
188
189def find_module(name, path=None):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400190 """**DEPRECATED**
191
192 Search for a module.
Brett Cannone69f0df2012-04-21 21:09:46 -0400193
194 If path is omitted or None, search for a built-in, frozen or special
195 module and continue search in sys.path. The module name cannot
196 contain '.'; to search for a submodule of a package, pass the
197 submodule name and the package's __path__.
198
199 """
200 if not isinstance(name, str):
201 raise TypeError("'name' must be a str, not {}".format(type(name)))
202 elif not isinstance(path, (type(None), list)):
203 # Backwards-compatibility
204 raise RuntimeError("'list' must be None or a list, "
205 "not {}".format(type(name)))
206
207 if path is None:
208 if is_builtin(name):
209 return None, None, ('', '', C_BUILTIN)
210 elif is_frozen(name):
211 return None, None, ('', '', PY_FROZEN)
212 else:
213 path = sys.path
214
215 for entry in path:
216 package_directory = os.path.join(entry, name)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400217 for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
Brett Cannone69f0df2012-04-21 21:09:46 -0400218 package_file_name = '__init__' + suffix
219 file_path = os.path.join(package_directory, package_file_name)
220 if os.path.isfile(file_path):
221 return None, package_directory, ('', '', PKG_DIRECTORY)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400222 with warnings.catch_warnings():
223 warnings.simplefilter('ignore')
224 for suffix, mode, type_ in get_suffixes():
225 file_name = name + suffix
226 file_path = os.path.join(entry, file_name)
227 if os.path.isfile(file_path):
228 break
229 else:
230 continue
231 break # Break out of outer loop when breaking out of inner loop.
Brett Cannone69f0df2012-04-21 21:09:46 -0400232 else:
233 raise ImportError('No module name {!r}'.format(name), name=name)
234
235 encoding = None
236 if mode == 'U':
237 with open(file_path, 'rb') as file:
238 encoding = tokenize.detect_encoding(file.readline)[0]
239 file = open(file_path, mode, encoding=encoding)
240 return file, file_path, (suffix, mode, type_)
Brett Cannon62228db2012-04-29 14:38:11 -0400241
242
243_RELOADING = {}
244
245def reload(module):
246 """Reload the module and return it.
247
248 The module must have been successfully imported before.
249
250 """
251 if not module or type(module) != type(sys):
252 raise TypeError("reload() argument must be module")
253 name = module.__name__
254 if name not in sys.modules:
255 msg = "module {} not in sys.modules"
256 raise ImportError(msg.format(name), name=name)
257 if name in _RELOADING:
258 return _RELOADING[name]
259 _RELOADING[name] = module
260 try:
261 parent_name = name.rpartition('.')[0]
262 if parent_name and parent_name not in sys.modules:
263 msg = "parent {!r} not in sys.modules"
264 raise ImportError(msg.format(parentname), name=parent_name)
265 return module.__loader__.load_module(name)
266 finally:
267 try:
268 del _RELOADING[name]
269 except KeyError:
270 pass