blob: 7a7079f71d587aea34d45f284b25c3df04e85f21 [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 Cannon3e2fe052013-03-17 15:48:16 -070010 get_frozen_object, is_frozen_package,
Brett Cannon2fef4d22012-04-15 19:06:23 -040011 init_builtin, init_frozen, is_builtin, is_frozen,
Brett Cannonac9f2f32012-08-10 13:47:54 -040012 _fix_co_filename)
Brett Cannon3e2fe052013-03-17 15:48:16 -070013try:
14 from _imp import load_dynamic
15except ImportError:
16 # Platform doesn't support dynamic loading.
17 load_dynamic = None
Brett Cannon6f44d662012-04-15 16:08:47 -040018
Brett Cannon77b2abd2012-07-09 16:09:00 -040019# Directly exposed by this module
Brett Cannon17098a52012-05-04 13:52:49 -040020from importlib._bootstrap import new_module
Brett Cannona6473f92012-07-13 13:57:03 -040021from importlib._bootstrap import cache_from_source, source_from_cache
Brett Cannon01a76172012-04-15 20:25:23 -040022
Brett Cannon77b2abd2012-07-09 16:09:00 -040023
Brett Cannon2ee61422012-04-15 22:28:28 -040024from importlib import _bootstrap
Brett Cannoncb66eb02012-05-11 12:58:42 -040025from importlib import machinery
Brett Cannon2ee61422012-04-15 22:28:28 -040026import os
Brett Cannone69f0df2012-04-21 21:09:46 -040027import sys
28import tokenize
Brett Cannoncb66eb02012-05-11 12:58:42 -040029import warnings
Brett Cannone69f0df2012-04-21 21:09:46 -040030
31
Brett Cannonc0499522012-05-11 14:48:41 -040032# DEPRECATED
Brett Cannone69f0df2012-04-21 21:09:46 -040033SEARCH_ERROR = 0
34PY_SOURCE = 1
35PY_COMPILED = 2
36C_EXTENSION = 3
37PY_RESOURCE = 4
38PKG_DIRECTORY = 5
39C_BUILTIN = 6
40PY_FROZEN = 7
41PY_CODERESOURCE = 8
42IMP_HOOK = 9
Brett Cannon2ee61422012-04-15 22:28:28 -040043
44
Brett Cannon77b2abd2012-07-09 16:09:00 -040045def get_magic():
46 """Return the magic number for .pyc or .pyo files."""
47 return _bootstrap._MAGIC_BYTES
48
49
Brett Cannon98979b82012-07-02 15:13:11 -040050def get_tag():
51 """Return the magic tag for .pyc or .pyo files."""
52 return sys.implementation.cache_tag
53
54
Brett Cannon2657df42012-05-04 15:20:40 -040055def get_suffixes():
Brett Cannoncb66eb02012-05-11 12:58:42 -040056 warnings.warn('imp.get_suffixes() is deprecated; use the constants '
57 'defined on importlib.machinery instead',
58 DeprecationWarning, 2)
Brett Cannonac9f2f32012-08-10 13:47:54 -040059 extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES]
Brett Cannoncb66eb02012-05-11 12:58:42 -040060 source = [(s, 'U', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
61 bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
Brett Cannon2657df42012-05-04 15:20:40 -040062
63 return extensions + source + bytecode
64
65
Brett Cannonacf85cd2012-04-29 12:50:03 -040066class NullImporter:
67
68 """Null import object."""
69
70 def __init__(self, path):
71 if path == '':
72 raise ImportError('empty pathname', path='')
73 elif os.path.isdir(path):
74 raise ImportError('existing directory', path=path)
75
76 def find_module(self, fullname):
77 """Always returns None."""
78 return None
79
80
Brett Cannon64befe92012-04-17 19:14:26 -040081class _HackedGetData:
Brett Cannon16475ad2012-04-16 22:11:25 -040082
Brett Cannon64befe92012-04-17 19:14:26 -040083 """Compatibiilty support for 'file' arguments of various load_*()
84 functions."""
Brett Cannon16475ad2012-04-16 22:11:25 -040085
86 def __init__(self, fullname, path, file=None):
87 super().__init__(fullname, path)
88 self.file = file
89
90 def get_data(self, path):
Brett Cannon64befe92012-04-17 19:14:26 -040091 """Gross hack to contort loader to deal w/ load_*()'s bad API."""
Brett Cannon938d44d2012-04-22 19:58:33 -040092 if self.file and path == self.path:
Brett Cannon16475ad2012-04-16 22:11:25 -040093 with self.file:
94 # Technically should be returning bytes, but
95 # SourceLoader.get_code() just passed what is returned to
96 # compile() which can handle str. And converting to bytes would
97 # require figuring out the encoding to decode to and
98 # tokenize.detect_encoding() only accepts bytes.
99 return self.file.read()
100 else:
101 return super().get_data(path)
102
103
Brett Cannon938d44d2012-04-22 19:58:33 -0400104class _LoadSourceCompatibility(_HackedGetData, _bootstrap.SourceFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400105
106 """Compatibility support for implementing load_source()."""
107
108
Brett Cannon16475ad2012-04-16 22:11:25 -0400109def load_source(name, pathname, file=None):
Brett Cannonc0499522012-05-11 14:48:41 -0400110 msg = ('imp.load_source() is deprecated; use '
111 'importlib.machinery.SourceFileLoader(name, pathname).load_module()'
112 ' instead')
113 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon16475ad2012-04-16 22:11:25 -0400114 return _LoadSourceCompatibility(name, pathname, file).load_module(name)
115
116
Brett Cannon64befe92012-04-17 19:14:26 -0400117class _LoadCompiledCompatibility(_HackedGetData,
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200118 _bootstrap.SourcelessFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400119
120 """Compatibility support for implementing load_compiled()."""
121
122
123def load_compiled(name, pathname, file=None):
Brett Cannonc0499522012-05-11 14:48:41 -0400124 msg = ('imp.load_compiled() is deprecated; use '
125 'importlib.machinery.SourcelessFileLoader(name, pathname).'
126 'load_module() instead ')
127 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon64befe92012-04-17 19:14:26 -0400128 return _LoadCompiledCompatibility(name, pathname, file).load_module(name)
129
130
Brett Cannon2ee61422012-04-15 22:28:28 -0400131def load_package(name, path):
Brett Cannonc0499522012-05-11 14:48:41 -0400132 msg = ('imp.load_package() is deprecated; use either '
133 'importlib.machinery.SourceFileLoader() or '
134 'importlib.machinery.SourcelessFileLoader() instead')
135 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon2ee61422012-04-15 22:28:28 -0400136 if os.path.isdir(path):
Brett Cannonc0499522012-05-11 14:48:41 -0400137 extensions = (machinery.SOURCE_SUFFIXES[:] +
138 machinery.BYTECODE_SUFFIXES[:])
Brett Cannon2ee61422012-04-15 22:28:28 -0400139 for extension in extensions:
140 path = os.path.join(path, '__init__'+extension)
141 if os.path.exists(path):
142 break
143 else:
144 raise ValueError('{!r} is not a package'.format(path))
Brett Cannon938d44d2012-04-22 19:58:33 -0400145 return _bootstrap.SourceFileLoader(name, path).load_module(name)
Brett Cannon2ee61422012-04-15 22:28:28 -0400146
Brett Cannon01a76172012-04-15 20:25:23 -0400147
148def load_module(name, file, filename, details):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400149 """**DEPRECATED**
150
151 Load a module, given information returned by find_module().
Brett Cannon01a76172012-04-15 20:25:23 -0400152
153 The module name must include the full package name, if any.
154
155 """
156 suffix, mode, type_ = details
Brett Cannonc0499522012-05-11 14:48:41 -0400157 with warnings.catch_warnings():
158 warnings.simplefilter('ignore')
159 if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
160 raise ValueError('invalid file open mode {!r}'.format(mode))
Nick Coghlan91b9f132012-09-01 00:13:45 +1000161 elif file is None and type_ in {PY_SOURCE, PY_COMPILED, C_EXTENSION}:
Brett Cannonc0499522012-05-11 14:48:41 -0400162 msg = 'file object required for import (type code {})'.format(type_)
163 raise ValueError(msg)
164 elif type_ == PY_SOURCE:
165 return load_source(name, filename, file)
166 elif type_ == PY_COMPILED:
167 return load_compiled(name, filename, file)
Brett Cannon3e2fe052013-03-17 15:48:16 -0700168 elif type_ == C_EXTENSION and load_dynamic is not None:
Nick Coghlan91b9f132012-09-01 00:13:45 +1000169 return load_dynamic(name, filename, file)
Brett Cannonc0499522012-05-11 14:48:41 -0400170 elif type_ == PKG_DIRECTORY:
171 return load_package(name, filename)
172 elif type_ == C_BUILTIN:
173 return init_builtin(name)
174 elif type_ == PY_FROZEN:
175 return init_frozen(name)
176 else:
Nick Coghlan91b9f132012-09-01 00:13:45 +1000177 msg = "Don't know how to import {} (type code {})".format(name, type_)
Brett Cannonc0499522012-05-11 14:48:41 -0400178 raise ImportError(msg, name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400179
180
181def find_module(name, path=None):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400182 """**DEPRECATED**
183
184 Search for a module.
Brett Cannone69f0df2012-04-21 21:09:46 -0400185
186 If path is omitted or None, search for a built-in, frozen or special
187 module and continue search in sys.path. The module name cannot
188 contain '.'; to search for a submodule of a package, pass the
189 submodule name and the package's __path__.
190
191 """
192 if not isinstance(name, str):
193 raise TypeError("'name' must be a str, not {}".format(type(name)))
194 elif not isinstance(path, (type(None), list)):
195 # Backwards-compatibility
196 raise RuntimeError("'list' must be None or a list, "
197 "not {}".format(type(name)))
198
199 if path is None:
200 if is_builtin(name):
201 return None, None, ('', '', C_BUILTIN)
202 elif is_frozen(name):
203 return None, None, ('', '', PY_FROZEN)
204 else:
205 path = sys.path
206
207 for entry in path:
208 package_directory = os.path.join(entry, name)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400209 for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
Brett Cannone69f0df2012-04-21 21:09:46 -0400210 package_file_name = '__init__' + suffix
211 file_path = os.path.join(package_directory, package_file_name)
212 if os.path.isfile(file_path):
213 return None, package_directory, ('', '', PKG_DIRECTORY)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400214 with warnings.catch_warnings():
215 warnings.simplefilter('ignore')
216 for suffix, mode, type_ in get_suffixes():
217 file_name = name + suffix
218 file_path = os.path.join(entry, file_name)
219 if os.path.isfile(file_path):
220 break
221 else:
222 continue
223 break # Break out of outer loop when breaking out of inner loop.
Brett Cannone69f0df2012-04-21 21:09:46 -0400224 else:
Brett Cannonbf7eab02012-07-09 13:24:34 -0400225 raise ImportError(_bootstrap._ERR_MSG.format(name), name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400226
227 encoding = None
228 if mode == 'U':
229 with open(file_path, 'rb') as file:
230 encoding = tokenize.detect_encoding(file.readline)[0]
231 file = open(file_path, mode, encoding=encoding)
232 return file, file_path, (suffix, mode, type_)
Brett Cannon62228db2012-04-29 14:38:11 -0400233
234
235_RELOADING = {}
236
237def reload(module):
238 """Reload the module and return it.
239
240 The module must have been successfully imported before.
241
242 """
243 if not module or type(module) != type(sys):
244 raise TypeError("reload() argument must be module")
245 name = module.__name__
246 if name not in sys.modules:
247 msg = "module {} not in sys.modules"
248 raise ImportError(msg.format(name), name=name)
249 if name in _RELOADING:
250 return _RELOADING[name]
251 _RELOADING[name] = module
252 try:
253 parent_name = name.rpartition('.')[0]
254 if parent_name and parent_name not in sys.modules:
255 msg = "parent {!r} not in sys.modules"
256 raise ImportError(msg.format(parentname), name=parent_name)
257 return module.__loader__.load_module(name)
258 finally:
259 try:
260 del _RELOADING[name]
261 except KeyError:
262 pass