blob: 58d1c974cf3492e931a5386170f11ff972d306d4 [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 Cannon6f44d662012-04-15 16:08:47 -040013
Brett Cannon77b2abd2012-07-09 16:09:00 -040014# Directly exposed by this module
Brett Cannon17098a52012-05-04 13:52:49 -040015from importlib._bootstrap import new_module
16from importlib._bootstrap import cache_from_source
Brett Cannon01a76172012-04-15 20:25:23 -040017
Brett Cannon77b2abd2012-07-09 16:09:00 -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 Cannon77b2abd2012-07-09 16:09:00 -040040def get_magic():
41 """Return the magic number for .pyc or .pyo files."""
42 return _bootstrap._MAGIC_BYTES
43
44
Brett Cannon98979b82012-07-02 15:13:11 -040045def get_tag():
46 """Return the magic tag for .pyc or .pyo files."""
47 return sys.implementation.cache_tag
48
49
Brett Cannon2657df42012-05-04 15:20:40 -040050def get_suffixes():
Brett Cannoncb66eb02012-05-11 12:58:42 -040051 warnings.warn('imp.get_suffixes() is deprecated; use the constants '
52 'defined on importlib.machinery instead',
53 DeprecationWarning, 2)
Brett Cannon2657df42012-05-04 15:20:40 -040054 extensions = [(s, 'rb', C_EXTENSION) for s in extension_suffixes()]
Brett Cannoncb66eb02012-05-11 12:58:42 -040055 source = [(s, 'U', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
56 bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
Brett Cannon2657df42012-05-04 15:20:40 -040057
58 return extensions + source + bytecode
59
60
Brett Cannona64faf02012-04-21 18:52:52 -040061def source_from_cache(path):
62 """Given the path to a .pyc./.pyo file, return the path to its .py file.
63
64 The .pyc/.pyo file does not need to exist; this simply returns the path to
65 the .py file calculated to correspond to the .pyc/.pyo file. If path does
Brett Cannon19a2f592012-07-09 13:58:07 -040066 not conform to PEP 3147 format, ValueError will be raised. If
67 sys.implementation.cache_tag is None then NotImplementedError is raised.
Brett Cannona64faf02012-04-21 18:52:52 -040068
69 """
Brett Cannon19a2f592012-07-09 13:58:07 -040070 if sys.implementation.cache_tag is None:
71 raise NotImplementedError('sys.implementation.cache_tag is None')
Brett Cannona64faf02012-04-21 18:52:52 -040072 head, pycache_filename = os.path.split(path)
73 head, pycache = os.path.split(head)
Brett Cannon17098a52012-05-04 13:52:49 -040074 if pycache != _bootstrap._PYCACHE:
Brett Cannona64faf02012-04-21 18:52:52 -040075 raise ValueError('{} not bottom-level directory in '
Brett Cannon17098a52012-05-04 13:52:49 -040076 '{!r}'.format(_bootstrap._PYCACHE, path))
Brett Cannona64faf02012-04-21 18:52:52 -040077 if pycache_filename.count('.') != 2:
78 raise ValueError('expected only 2 dots in '
79 '{!r}'.format(pycache_filename))
80 base_filename = pycache_filename.partition('.')[0]
Brett Cannoncb66eb02012-05-11 12:58:42 -040081 return os.path.join(head, base_filename + machinery.SOURCE_SUFFIXES[0])
Brett Cannona64faf02012-04-21 18:52:52 -040082
83
Brett Cannonacf85cd2012-04-29 12:50:03 -040084class NullImporter:
85
86 """Null import object."""
87
88 def __init__(self, path):
89 if path == '':
90 raise ImportError('empty pathname', path='')
91 elif os.path.isdir(path):
92 raise ImportError('existing directory', path=path)
93
94 def find_module(self, fullname):
95 """Always returns None."""
96 return None
97
98
Brett Cannon64befe92012-04-17 19:14:26 -040099class _HackedGetData:
Brett Cannon16475ad2012-04-16 22:11:25 -0400100
Brett Cannon64befe92012-04-17 19:14:26 -0400101 """Compatibiilty support for 'file' arguments of various load_*()
102 functions."""
Brett Cannon16475ad2012-04-16 22:11:25 -0400103
104 def __init__(self, fullname, path, file=None):
105 super().__init__(fullname, path)
106 self.file = file
107
108 def get_data(self, path):
Brett Cannon64befe92012-04-17 19:14:26 -0400109 """Gross hack to contort loader to deal w/ load_*()'s bad API."""
Brett Cannon938d44d2012-04-22 19:58:33 -0400110 if self.file and path == self.path:
Brett Cannon16475ad2012-04-16 22:11:25 -0400111 with self.file:
112 # Technically should be returning bytes, but
113 # SourceLoader.get_code() just passed what is returned to
114 # compile() which can handle str. And converting to bytes would
115 # require figuring out the encoding to decode to and
116 # tokenize.detect_encoding() only accepts bytes.
117 return self.file.read()
118 else:
119 return super().get_data(path)
120
121
Brett Cannon938d44d2012-04-22 19:58:33 -0400122class _LoadSourceCompatibility(_HackedGetData, _bootstrap.SourceFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400123
124 """Compatibility support for implementing load_source()."""
125
126
Brett Cannon16475ad2012-04-16 22:11:25 -0400127def load_source(name, pathname, file=None):
Brett Cannonc0499522012-05-11 14:48:41 -0400128 msg = ('imp.load_source() is deprecated; use '
129 'importlib.machinery.SourceFileLoader(name, pathname).load_module()'
130 ' instead')
131 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon16475ad2012-04-16 22:11:25 -0400132 return _LoadSourceCompatibility(name, pathname, file).load_module(name)
133
134
Brett Cannon64befe92012-04-17 19:14:26 -0400135class _LoadCompiledCompatibility(_HackedGetData,
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200136 _bootstrap.SourcelessFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400137
138 """Compatibility support for implementing load_compiled()."""
139
140
141def load_compiled(name, pathname, file=None):
Brett Cannonc0499522012-05-11 14:48:41 -0400142 msg = ('imp.load_compiled() is deprecated; use '
143 'importlib.machinery.SourcelessFileLoader(name, pathname).'
144 'load_module() instead ')
145 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon64befe92012-04-17 19:14:26 -0400146 return _LoadCompiledCompatibility(name, pathname, file).load_module(name)
147
148
Brett Cannon2ee61422012-04-15 22:28:28 -0400149def load_package(name, path):
Brett Cannonc0499522012-05-11 14:48:41 -0400150 msg = ('imp.load_package() is deprecated; use either '
151 'importlib.machinery.SourceFileLoader() or '
152 'importlib.machinery.SourcelessFileLoader() instead')
153 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon2ee61422012-04-15 22:28:28 -0400154 if os.path.isdir(path):
Brett Cannonc0499522012-05-11 14:48:41 -0400155 extensions = (machinery.SOURCE_SUFFIXES[:] +
156 machinery.BYTECODE_SUFFIXES[:])
Brett Cannon2ee61422012-04-15 22:28:28 -0400157 for extension in extensions:
158 path = os.path.join(path, '__init__'+extension)
159 if os.path.exists(path):
160 break
161 else:
162 raise ValueError('{!r} is not a package'.format(path))
Brett Cannon938d44d2012-04-22 19:58:33 -0400163 return _bootstrap.SourceFileLoader(name, path).load_module(name)
Brett Cannon2ee61422012-04-15 22:28:28 -0400164
Brett Cannon01a76172012-04-15 20:25:23 -0400165
166def load_module(name, file, filename, details):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400167 """**DEPRECATED**
168
169 Load a module, given information returned by find_module().
Brett Cannon01a76172012-04-15 20:25:23 -0400170
171 The module name must include the full package name, if any.
172
173 """
174 suffix, mode, type_ = details
Brett Cannonc0499522012-05-11 14:48:41 -0400175 with warnings.catch_warnings():
176 warnings.simplefilter('ignore')
177 if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
178 raise ValueError('invalid file open mode {!r}'.format(mode))
179 elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
180 msg = 'file object required for import (type code {})'.format(type_)
181 raise ValueError(msg)
182 elif type_ == PY_SOURCE:
183 return load_source(name, filename, file)
184 elif type_ == PY_COMPILED:
185 return load_compiled(name, filename, file)
186 elif type_ == PKG_DIRECTORY:
187 return load_package(name, filename)
188 elif type_ == C_BUILTIN:
189 return init_builtin(name)
190 elif type_ == PY_FROZEN:
191 return init_frozen(name)
192 else:
193 msg = "Don't know how to import {} (type code {}".format(name, type_)
194 raise ImportError(msg, name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400195
196
197def find_module(name, path=None):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400198 """**DEPRECATED**
199
200 Search for a module.
Brett Cannone69f0df2012-04-21 21:09:46 -0400201
202 If path is omitted or None, search for a built-in, frozen or special
203 module and continue search in sys.path. The module name cannot
204 contain '.'; to search for a submodule of a package, pass the
205 submodule name and the package's __path__.
206
207 """
208 if not isinstance(name, str):
209 raise TypeError("'name' must be a str, not {}".format(type(name)))
210 elif not isinstance(path, (type(None), list)):
211 # Backwards-compatibility
212 raise RuntimeError("'list' must be None or a list, "
213 "not {}".format(type(name)))
214
215 if path is None:
216 if is_builtin(name):
217 return None, None, ('', '', C_BUILTIN)
218 elif is_frozen(name):
219 return None, None, ('', '', PY_FROZEN)
220 else:
221 path = sys.path
222
223 for entry in path:
224 package_directory = os.path.join(entry, name)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400225 for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
Brett Cannone69f0df2012-04-21 21:09:46 -0400226 package_file_name = '__init__' + suffix
227 file_path = os.path.join(package_directory, package_file_name)
228 if os.path.isfile(file_path):
229 return None, package_directory, ('', '', PKG_DIRECTORY)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400230 with warnings.catch_warnings():
231 warnings.simplefilter('ignore')
232 for suffix, mode, type_ in get_suffixes():
233 file_name = name + suffix
234 file_path = os.path.join(entry, file_name)
235 if os.path.isfile(file_path):
236 break
237 else:
238 continue
239 break # Break out of outer loop when breaking out of inner loop.
Brett Cannone69f0df2012-04-21 21:09:46 -0400240 else:
Brett Cannonbf7eab02012-07-09 13:24:34 -0400241 raise ImportError(_bootstrap._ERR_MSG.format(name), name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400242
243 encoding = None
244 if mode == 'U':
245 with open(file_path, 'rb') as file:
246 encoding = tokenize.detect_encoding(file.readline)[0]
247 file = open(file_path, mode, encoding=encoding)
248 return file, file_path, (suffix, mode, type_)
Brett Cannon62228db2012-04-29 14:38:11 -0400249
250
251_RELOADING = {}
252
253def reload(module):
254 """Reload the module and return it.
255
256 The module must have been successfully imported before.
257
258 """
259 if not module or type(module) != type(sys):
260 raise TypeError("reload() argument must be module")
261 name = module.__name__
262 if name not in sys.modules:
263 msg = "module {} not in sys.modules"
264 raise ImportError(msg.format(name), name=name)
265 if name in _RELOADING:
266 return _RELOADING[name]
267 _RELOADING[name] = module
268 try:
269 parent_name = name.rpartition('.')[0]
270 if parent_name and parent_name not in sys.modules:
271 msg = "parent {!r} not in sys.modules"
272 raise ImportError(msg.format(parentname), name=parent_name)
273 return module.__loader__.load_module(name)
274 finally:
275 try:
276 del _RELOADING[name]
277 except KeyError:
278 pass