blob: 8c89237f07b1a6ab532b06e1f11e6e608251ed1e [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 Cannon2f923892012-04-21 18:55:51 -040014from _imp import get_magic, get_tag
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 Cannon2657df42012-05-04 15:20:40 -040040def get_suffixes():
Brett Cannoncb66eb02012-05-11 12:58:42 -040041 warnings.warn('imp.get_suffixes() is deprecated; use the constants '
42 'defined on importlib.machinery instead',
43 DeprecationWarning, 2)
Brett Cannon2657df42012-05-04 15:20:40 -040044 extensions = [(s, 'rb', C_EXTENSION) for s in extension_suffixes()]
Brett Cannoncb66eb02012-05-11 12:58:42 -040045 source = [(s, 'U', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
46 bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
Brett Cannon2657df42012-05-04 15:20:40 -040047
48 return extensions + source + bytecode
49
50
Brett Cannona64faf02012-04-21 18:52:52 -040051def source_from_cache(path):
52 """Given the path to a .pyc./.pyo file, return the path to its .py file.
53
54 The .pyc/.pyo file does not need to exist; this simply returns the path to
55 the .py file calculated to correspond to the .pyc/.pyo file. If path does
56 not conform to PEP 3147 format, ValueError will be raised.
57
58 """
59 head, pycache_filename = os.path.split(path)
60 head, pycache = os.path.split(head)
Brett Cannon17098a52012-05-04 13:52:49 -040061 if pycache != _bootstrap._PYCACHE:
Brett Cannona64faf02012-04-21 18:52:52 -040062 raise ValueError('{} not bottom-level directory in '
Brett Cannon17098a52012-05-04 13:52:49 -040063 '{!r}'.format(_bootstrap._PYCACHE, path))
Brett Cannona64faf02012-04-21 18:52:52 -040064 if pycache_filename.count('.') != 2:
65 raise ValueError('expected only 2 dots in '
66 '{!r}'.format(pycache_filename))
67 base_filename = pycache_filename.partition('.')[0]
Brett Cannoncb66eb02012-05-11 12:58:42 -040068 return os.path.join(head, base_filename + machinery.SOURCE_SUFFIXES[0])
Brett Cannona64faf02012-04-21 18:52:52 -040069
70
Brett Cannonacf85cd2012-04-29 12:50:03 -040071class NullImporter:
72
73 """Null import object."""
74
75 def __init__(self, path):
76 if path == '':
77 raise ImportError('empty pathname', path='')
78 elif os.path.isdir(path):
79 raise ImportError('existing directory', path=path)
80
81 def find_module(self, fullname):
82 """Always returns None."""
83 return None
84
85
Brett Cannon64befe92012-04-17 19:14:26 -040086class _HackedGetData:
Brett Cannon16475ad2012-04-16 22:11:25 -040087
Brett Cannon64befe92012-04-17 19:14:26 -040088 """Compatibiilty support for 'file' arguments of various load_*()
89 functions."""
Brett Cannon16475ad2012-04-16 22:11:25 -040090
91 def __init__(self, fullname, path, file=None):
92 super().__init__(fullname, path)
93 self.file = file
94
95 def get_data(self, path):
Brett Cannon64befe92012-04-17 19:14:26 -040096 """Gross hack to contort loader to deal w/ load_*()'s bad API."""
Brett Cannon938d44d2012-04-22 19:58:33 -040097 if self.file and path == self.path:
Brett Cannon16475ad2012-04-16 22:11:25 -040098 with self.file:
99 # Technically should be returning bytes, but
100 # SourceLoader.get_code() just passed what is returned to
101 # compile() which can handle str. And converting to bytes would
102 # require figuring out the encoding to decode to and
103 # tokenize.detect_encoding() only accepts bytes.
104 return self.file.read()
105 else:
106 return super().get_data(path)
107
108
Brett Cannon938d44d2012-04-22 19:58:33 -0400109class _LoadSourceCompatibility(_HackedGetData, _bootstrap.SourceFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400110
111 """Compatibility support for implementing load_source()."""
112
113
Brett Cannon16475ad2012-04-16 22:11:25 -0400114def load_source(name, pathname, file=None):
Brett Cannonc0499522012-05-11 14:48:41 -0400115 msg = ('imp.load_source() is deprecated; use '
116 'importlib.machinery.SourceFileLoader(name, pathname).load_module()'
117 ' instead')
118 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon16475ad2012-04-16 22:11:25 -0400119 return _LoadSourceCompatibility(name, pathname, file).load_module(name)
120
121
Brett Cannon64befe92012-04-17 19:14:26 -0400122class _LoadCompiledCompatibility(_HackedGetData,
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200123 _bootstrap.SourcelessFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400124
125 """Compatibility support for implementing load_compiled()."""
126
127
128def load_compiled(name, pathname, file=None):
Brett Cannonc0499522012-05-11 14:48:41 -0400129 msg = ('imp.load_compiled() is deprecated; use '
130 'importlib.machinery.SourcelessFileLoader(name, pathname).'
131 'load_module() instead ')
132 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon64befe92012-04-17 19:14:26 -0400133 return _LoadCompiledCompatibility(name, pathname, file).load_module(name)
134
135
Brett Cannon2ee61422012-04-15 22:28:28 -0400136def load_package(name, path):
Brett Cannonc0499522012-05-11 14:48:41 -0400137 msg = ('imp.load_package() is deprecated; use either '
138 'importlib.machinery.SourceFileLoader() or '
139 'importlib.machinery.SourcelessFileLoader() instead')
140 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon2ee61422012-04-15 22:28:28 -0400141 if os.path.isdir(path):
Brett Cannonc0499522012-05-11 14:48:41 -0400142 extensions = (machinery.SOURCE_SUFFIXES[:] +
143 machinery.BYTECODE_SUFFIXES[:])
Brett Cannon2ee61422012-04-15 22:28:28 -0400144 for extension in extensions:
145 path = os.path.join(path, '__init__'+extension)
146 if os.path.exists(path):
147 break
148 else:
149 raise ValueError('{!r} is not a package'.format(path))
Brett Cannon938d44d2012-04-22 19:58:33 -0400150 return _bootstrap.SourceFileLoader(name, path).load_module(name)
Brett Cannon2ee61422012-04-15 22:28:28 -0400151
Brett Cannon01a76172012-04-15 20:25:23 -0400152
153def load_module(name, file, filename, details):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400154 """**DEPRECATED**
155
156 Load a module, given information returned by find_module().
Brett Cannon01a76172012-04-15 20:25:23 -0400157
158 The module name must include the full package name, if any.
159
160 """
161 suffix, mode, type_ = details
Brett Cannonc0499522012-05-11 14:48:41 -0400162 with warnings.catch_warnings():
163 warnings.simplefilter('ignore')
164 if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
165 raise ValueError('invalid file open mode {!r}'.format(mode))
166 elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
167 msg = 'file object required for import (type code {})'.format(type_)
168 raise ValueError(msg)
169 elif type_ == PY_SOURCE:
170 return load_source(name, filename, file)
171 elif type_ == PY_COMPILED:
172 return load_compiled(name, filename, file)
173 elif type_ == PKG_DIRECTORY:
174 return load_package(name, filename)
175 elif type_ == C_BUILTIN:
176 return init_builtin(name)
177 elif type_ == PY_FROZEN:
178 return init_frozen(name)
179 else:
180 msg = "Don't know how to import {} (type code {}".format(name, type_)
181 raise ImportError(msg, name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400182
183
184def find_module(name, path=None):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400185 """**DEPRECATED**
186
187 Search for a module.
Brett Cannone69f0df2012-04-21 21:09:46 -0400188
189 If path is omitted or None, search for a built-in, frozen or special
190 module and continue search in sys.path. The module name cannot
191 contain '.'; to search for a submodule of a package, pass the
192 submodule name and the package's __path__.
193
194 """
195 if not isinstance(name, str):
196 raise TypeError("'name' must be a str, not {}".format(type(name)))
197 elif not isinstance(path, (type(None), list)):
198 # Backwards-compatibility
199 raise RuntimeError("'list' must be None or a list, "
200 "not {}".format(type(name)))
201
202 if path is None:
203 if is_builtin(name):
204 return None, None, ('', '', C_BUILTIN)
205 elif is_frozen(name):
206 return None, None, ('', '', PY_FROZEN)
207 else:
208 path = sys.path
209
210 for entry in path:
211 package_directory = os.path.join(entry, name)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400212 for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
Brett Cannone69f0df2012-04-21 21:09:46 -0400213 package_file_name = '__init__' + suffix
214 file_path = os.path.join(package_directory, package_file_name)
215 if os.path.isfile(file_path):
216 return None, package_directory, ('', '', PKG_DIRECTORY)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400217 with warnings.catch_warnings():
218 warnings.simplefilter('ignore')
219 for suffix, mode, type_ in get_suffixes():
220 file_name = name + suffix
221 file_path = os.path.join(entry, file_name)
222 if os.path.isfile(file_path):
223 break
224 else:
225 continue
226 break # Break out of outer loop when breaking out of inner loop.
Brett Cannone69f0df2012-04-21 21:09:46 -0400227 else:
228 raise ImportError('No module name {!r}'.format(name), name=name)
229
230 encoding = None
231 if mode == 'U':
232 with open(file_path, 'rb') as file:
233 encoding = tokenize.detect_encoding(file.readline)[0]
234 file = open(file_path, mode, encoding=encoding)
235 return file, file_path, (suffix, mode, type_)
Brett Cannon62228db2012-04-29 14:38:11 -0400236
237
238_RELOADING = {}
239
240def reload(module):
241 """Reload the module and return it.
242
243 The module must have been successfully imported before.
244
245 """
246 if not module or type(module) != type(sys):
247 raise TypeError("reload() argument must be module")
248 name = module.__name__
249 if name not in sys.modules:
250 msg = "module {} not in sys.modules"
251 raise ImportError(msg.format(name), name=name)
252 if name in _RELOADING:
253 return _RELOADING[name]
254 _RELOADING[name] = module
255 try:
256 parent_name = name.rpartition('.')[0]
257 if parent_name and parent_name not in sys.modules:
258 msg = "parent {!r} not in sys.modules"
259 raise ImportError(msg.format(parentname), name=parent_name)
260 return module.__loader__.load_module(name)
261 finally:
262 try:
263 del _RELOADING[name]
264 except KeyError:
265 pass