blob: dab83120837a71616ae6946529560e9bb746a48f [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
Brett Cannon19a2f592012-07-09 13:58:07 -040061 not conform to PEP 3147 format, ValueError will be raised. If
62 sys.implementation.cache_tag is None then NotImplementedError is raised.
Brett Cannona64faf02012-04-21 18:52:52 -040063
64 """
Brett Cannon19a2f592012-07-09 13:58:07 -040065 if sys.implementation.cache_tag is None:
66 raise NotImplementedError('sys.implementation.cache_tag is None')
Brett Cannona64faf02012-04-21 18:52:52 -040067 head, pycache_filename = os.path.split(path)
68 head, pycache = os.path.split(head)
Brett Cannon17098a52012-05-04 13:52:49 -040069 if pycache != _bootstrap._PYCACHE:
Brett Cannona64faf02012-04-21 18:52:52 -040070 raise ValueError('{} not bottom-level directory in '
Brett Cannon17098a52012-05-04 13:52:49 -040071 '{!r}'.format(_bootstrap._PYCACHE, path))
Brett Cannona64faf02012-04-21 18:52:52 -040072 if pycache_filename.count('.') != 2:
73 raise ValueError('expected only 2 dots in '
74 '{!r}'.format(pycache_filename))
75 base_filename = pycache_filename.partition('.')[0]
Brett Cannoncb66eb02012-05-11 12:58:42 -040076 return os.path.join(head, base_filename + machinery.SOURCE_SUFFIXES[0])
Brett Cannona64faf02012-04-21 18:52:52 -040077
78
Brett Cannonacf85cd2012-04-29 12:50:03 -040079class NullImporter:
80
81 """Null import object."""
82
83 def __init__(self, path):
84 if path == '':
85 raise ImportError('empty pathname', path='')
86 elif os.path.isdir(path):
87 raise ImportError('existing directory', path=path)
88
89 def find_module(self, fullname):
90 """Always returns None."""
91 return None
92
93
Brett Cannon64befe92012-04-17 19:14:26 -040094class _HackedGetData:
Brett Cannon16475ad2012-04-16 22:11:25 -040095
Brett Cannon64befe92012-04-17 19:14:26 -040096 """Compatibiilty support for 'file' arguments of various load_*()
97 functions."""
Brett Cannon16475ad2012-04-16 22:11:25 -040098
99 def __init__(self, fullname, path, file=None):
100 super().__init__(fullname, path)
101 self.file = file
102
103 def get_data(self, path):
Brett Cannon64befe92012-04-17 19:14:26 -0400104 """Gross hack to contort loader to deal w/ load_*()'s bad API."""
Brett Cannon938d44d2012-04-22 19:58:33 -0400105 if self.file and path == self.path:
Brett Cannon16475ad2012-04-16 22:11:25 -0400106 with self.file:
107 # Technically should be returning bytes, but
108 # SourceLoader.get_code() just passed what is returned to
109 # compile() which can handle str. And converting to bytes would
110 # require figuring out the encoding to decode to and
111 # tokenize.detect_encoding() only accepts bytes.
112 return self.file.read()
113 else:
114 return super().get_data(path)
115
116
Brett Cannon938d44d2012-04-22 19:58:33 -0400117class _LoadSourceCompatibility(_HackedGetData, _bootstrap.SourceFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400118
119 """Compatibility support for implementing load_source()."""
120
121
Brett Cannon16475ad2012-04-16 22:11:25 -0400122def load_source(name, pathname, file=None):
Brett Cannonc0499522012-05-11 14:48:41 -0400123 msg = ('imp.load_source() is deprecated; use '
124 'importlib.machinery.SourceFileLoader(name, pathname).load_module()'
125 ' instead')
126 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon16475ad2012-04-16 22:11:25 -0400127 return _LoadSourceCompatibility(name, pathname, file).load_module(name)
128
129
Brett Cannon64befe92012-04-17 19:14:26 -0400130class _LoadCompiledCompatibility(_HackedGetData,
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200131 _bootstrap.SourcelessFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400132
133 """Compatibility support for implementing load_compiled()."""
134
135
136def load_compiled(name, pathname, file=None):
Brett Cannonc0499522012-05-11 14:48:41 -0400137 msg = ('imp.load_compiled() is deprecated; use '
138 'importlib.machinery.SourcelessFileLoader(name, pathname).'
139 'load_module() instead ')
140 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon64befe92012-04-17 19:14:26 -0400141 return _LoadCompiledCompatibility(name, pathname, file).load_module(name)
142
143
Brett Cannon2ee61422012-04-15 22:28:28 -0400144def load_package(name, path):
Brett Cannonc0499522012-05-11 14:48:41 -0400145 msg = ('imp.load_package() is deprecated; use either '
146 'importlib.machinery.SourceFileLoader() or '
147 'importlib.machinery.SourcelessFileLoader() instead')
148 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon2ee61422012-04-15 22:28:28 -0400149 if os.path.isdir(path):
Brett Cannonc0499522012-05-11 14:48:41 -0400150 extensions = (machinery.SOURCE_SUFFIXES[:] +
151 machinery.BYTECODE_SUFFIXES[:])
Brett Cannon2ee61422012-04-15 22:28:28 -0400152 for extension in extensions:
153 path = os.path.join(path, '__init__'+extension)
154 if os.path.exists(path):
155 break
156 else:
157 raise ValueError('{!r} is not a package'.format(path))
Brett Cannon938d44d2012-04-22 19:58:33 -0400158 return _bootstrap.SourceFileLoader(name, path).load_module(name)
Brett Cannon2ee61422012-04-15 22:28:28 -0400159
Brett Cannon01a76172012-04-15 20:25:23 -0400160
161def load_module(name, file, filename, details):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400162 """**DEPRECATED**
163
164 Load a module, given information returned by find_module().
Brett Cannon01a76172012-04-15 20:25:23 -0400165
166 The module name must include the full package name, if any.
167
168 """
169 suffix, mode, type_ = details
Brett Cannonc0499522012-05-11 14:48:41 -0400170 with warnings.catch_warnings():
171 warnings.simplefilter('ignore')
172 if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
173 raise ValueError('invalid file open mode {!r}'.format(mode))
174 elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
175 msg = 'file object required for import (type code {})'.format(type_)
176 raise ValueError(msg)
177 elif type_ == PY_SOURCE:
178 return load_source(name, filename, file)
179 elif type_ == PY_COMPILED:
180 return load_compiled(name, filename, file)
181 elif type_ == PKG_DIRECTORY:
182 return load_package(name, filename)
183 elif type_ == C_BUILTIN:
184 return init_builtin(name)
185 elif type_ == PY_FROZEN:
186 return init_frozen(name)
187 else:
188 msg = "Don't know how to import {} (type code {}".format(name, type_)
189 raise ImportError(msg, name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400190
191
192def find_module(name, path=None):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400193 """**DEPRECATED**
194
195 Search for a module.
Brett Cannone69f0df2012-04-21 21:09:46 -0400196
197 If path is omitted or None, search for a built-in, frozen or special
198 module and continue search in sys.path. The module name cannot
199 contain '.'; to search for a submodule of a package, pass the
200 submodule name and the package's __path__.
201
202 """
203 if not isinstance(name, str):
204 raise TypeError("'name' must be a str, not {}".format(type(name)))
205 elif not isinstance(path, (type(None), list)):
206 # Backwards-compatibility
207 raise RuntimeError("'list' must be None or a list, "
208 "not {}".format(type(name)))
209
210 if path is None:
211 if is_builtin(name):
212 return None, None, ('', '', C_BUILTIN)
213 elif is_frozen(name):
214 return None, None, ('', '', PY_FROZEN)
215 else:
216 path = sys.path
217
218 for entry in path:
219 package_directory = os.path.join(entry, name)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400220 for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
Brett Cannone69f0df2012-04-21 21:09:46 -0400221 package_file_name = '__init__' + suffix
222 file_path = os.path.join(package_directory, package_file_name)
223 if os.path.isfile(file_path):
224 return None, package_directory, ('', '', PKG_DIRECTORY)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400225 with warnings.catch_warnings():
226 warnings.simplefilter('ignore')
227 for suffix, mode, type_ in get_suffixes():
228 file_name = name + suffix
229 file_path = os.path.join(entry, file_name)
230 if os.path.isfile(file_path):
231 break
232 else:
233 continue
234 break # Break out of outer loop when breaking out of inner loop.
Brett Cannone69f0df2012-04-21 21:09:46 -0400235 else:
Brett Cannonbf7eab02012-07-09 13:24:34 -0400236 raise ImportError(_bootstrap._ERR_MSG.format(name), name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400237
238 encoding = None
239 if mode == 'U':
240 with open(file_path, 'rb') as file:
241 encoding = tokenize.detect_encoding(file.readline)[0]
242 file = open(file_path, mode, encoding=encoding)
243 return file, file_path, (suffix, mode, type_)
Brett Cannon62228db2012-04-29 14:38:11 -0400244
245
246_RELOADING = {}
247
248def reload(module):
249 """Reload the module and return it.
250
251 The module must have been successfully imported before.
252
253 """
254 if not module or type(module) != type(sys):
255 raise TypeError("reload() argument must be module")
256 name = module.__name__
257 if name not in sys.modules:
258 msg = "module {} not in sys.modules"
259 raise ImportError(msg.format(name), name=name)
260 if name in _RELOADING:
261 return _RELOADING[name]
262 _RELOADING[name] = module
263 try:
264 parent_name = name.rpartition('.')[0]
265 if parent_name and parent_name not in sys.modules:
266 msg = "parent {!r} not in sys.modules"
267 raise ImportError(msg.format(parentname), name=parent_name)
268 return module.__loader__.load_module(name)
269 finally:
270 try:
271 del _RELOADING[name]
272 except KeyError:
273 pass