blob: f60f0508bac62b510a2dc0f58f508ec699a7b8bc [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
27# XXX "deprecate" once find_module(), load_module(), and get_suffixes() are
28# deprecated.
29SEARCH_ERROR = 0
30PY_SOURCE = 1
31PY_COMPILED = 2
32C_EXTENSION = 3
33PY_RESOURCE = 4
34PKG_DIRECTORY = 5
35C_BUILTIN = 6
36PY_FROZEN = 7
37PY_CODERESOURCE = 8
38IMP_HOOK = 9
Brett Cannon2ee61422012-04-15 22:28:28 -040039
40
Brett Cannon2657df42012-05-04 15:20:40 -040041def get_suffixes():
Brett Cannoncb66eb02012-05-11 12:58:42 -040042 warnings.warn('imp.get_suffixes() is deprecated; use the constants '
43 'defined on importlib.machinery instead',
44 DeprecationWarning, 2)
Brett Cannon2657df42012-05-04 15:20:40 -040045 extensions = [(s, 'rb', C_EXTENSION) for s in extension_suffixes()]
Brett Cannoncb66eb02012-05-11 12:58:42 -040046 source = [(s, 'U', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
47 bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
Brett Cannon2657df42012-05-04 15:20:40 -040048
49 return extensions + source + bytecode
50
51
Brett Cannona64faf02012-04-21 18:52:52 -040052def source_from_cache(path):
53 """Given the path to a .pyc./.pyo file, return the path to its .py file.
54
55 The .pyc/.pyo file does not need to exist; this simply returns the path to
56 the .py file calculated to correspond to the .pyc/.pyo file. If path does
57 not conform to PEP 3147 format, ValueError will be raised.
58
59 """
60 head, pycache_filename = os.path.split(path)
61 head, pycache = os.path.split(head)
Brett Cannon17098a52012-05-04 13:52:49 -040062 if pycache != _bootstrap._PYCACHE:
Brett Cannona64faf02012-04-21 18:52:52 -040063 raise ValueError('{} not bottom-level directory in '
Brett Cannon17098a52012-05-04 13:52:49 -040064 '{!r}'.format(_bootstrap._PYCACHE, path))
Brett Cannona64faf02012-04-21 18:52:52 -040065 if pycache_filename.count('.') != 2:
66 raise ValueError('expected only 2 dots in '
67 '{!r}'.format(pycache_filename))
68 base_filename = pycache_filename.partition('.')[0]
Brett Cannoncb66eb02012-05-11 12:58:42 -040069 return os.path.join(head, base_filename + machinery.SOURCE_SUFFIXES[0])
Brett Cannona64faf02012-04-21 18:52:52 -040070
71
Brett Cannonacf85cd2012-04-29 12:50:03 -040072class NullImporter:
73
74 """Null import object."""
75
76 def __init__(self, path):
77 if path == '':
78 raise ImportError('empty pathname', path='')
79 elif os.path.isdir(path):
80 raise ImportError('existing directory', path=path)
81
82 def find_module(self, fullname):
83 """Always returns None."""
84 return None
85
86
Brett Cannon64befe92012-04-17 19:14:26 -040087class _HackedGetData:
Brett Cannon16475ad2012-04-16 22:11:25 -040088
Brett Cannon64befe92012-04-17 19:14:26 -040089 """Compatibiilty support for 'file' arguments of various load_*()
90 functions."""
Brett Cannon16475ad2012-04-16 22:11:25 -040091
92 def __init__(self, fullname, path, file=None):
93 super().__init__(fullname, path)
94 self.file = file
95
96 def get_data(self, path):
Brett Cannon64befe92012-04-17 19:14:26 -040097 """Gross hack to contort loader to deal w/ load_*()'s bad API."""
Brett Cannon938d44d2012-04-22 19:58:33 -040098 if self.file and path == self.path:
Brett Cannon16475ad2012-04-16 22:11:25 -040099 with self.file:
100 # Technically should be returning bytes, but
101 # SourceLoader.get_code() just passed what is returned to
102 # compile() which can handle str. And converting to bytes would
103 # require figuring out the encoding to decode to and
104 # tokenize.detect_encoding() only accepts bytes.
105 return self.file.read()
106 else:
107 return super().get_data(path)
108
109
Brett Cannon938d44d2012-04-22 19:58:33 -0400110class _LoadSourceCompatibility(_HackedGetData, _bootstrap.SourceFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400111
112 """Compatibility support for implementing load_source()."""
113
114
Brett Cannona64faf02012-04-21 18:52:52 -0400115# XXX deprecate after better API exposed in importlib
Brett Cannon16475ad2012-04-16 22:11:25 -0400116def load_source(name, pathname, file=None):
117 return _LoadSourceCompatibility(name, pathname, file).load_module(name)
118
119
Brett Cannon64befe92012-04-17 19:14:26 -0400120class _LoadCompiledCompatibility(_HackedGetData,
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200121 _bootstrap.SourcelessFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400122
123 """Compatibility support for implementing load_compiled()."""
124
125
Brett Cannona64faf02012-04-21 18:52:52 -0400126# XXX deprecate
Brett Cannon64befe92012-04-17 19:14:26 -0400127def load_compiled(name, pathname, file=None):
128 return _LoadCompiledCompatibility(name, pathname, file).load_module(name)
129
130
Brett Cannona64faf02012-04-21 18:52:52 -0400131# XXX deprecate
Brett Cannon2ee61422012-04-15 22:28:28 -0400132def load_package(name, path):
133 if os.path.isdir(path):
Brett Cannoncb66eb02012-05-11 12:58:42 -0400134 extensions = machinery.SOURCE_SUFFIXES[:] + [machinery.BYTECODE_SUFFIXES]
Brett Cannon2ee61422012-04-15 22:28:28 -0400135 for extension in extensions:
136 path = os.path.join(path, '__init__'+extension)
137 if os.path.exists(path):
138 break
139 else:
140 raise ValueError('{!r} is not a package'.format(path))
Brett Cannon938d44d2012-04-22 19:58:33 -0400141 return _bootstrap.SourceFileLoader(name, path).load_module(name)
Brett Cannon2ee61422012-04-15 22:28:28 -0400142
Brett Cannon01a76172012-04-15 20:25:23 -0400143
Brett Cannona64faf02012-04-21 18:52:52 -0400144# XXX deprecate
Brett Cannon01a76172012-04-15 20:25:23 -0400145def load_module(name, file, filename, details):
146 """Load a module, given information returned by find_module().
147
148 The module name must include the full package name, if any.
149
150 """
151 suffix, mode, type_ = details
Brett Cannonde10bf42012-04-16 20:44:21 -0400152 if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
Brett Cannon01a76172012-04-15 20:25:23 -0400153 raise ValueError('invalid file open mode {!r}'.format(mode))
154 elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
155 msg = 'file object required for import (type code {})'.format(type_)
156 raise ValueError(msg)
157 elif type_ == PY_SOURCE:
158 return load_source(name, filename, file)
159 elif type_ == PY_COMPILED:
160 return load_compiled(name, filename, file)
161 elif type_ == PKG_DIRECTORY:
162 return load_package(name, filename)
163 elif type_ == C_BUILTIN:
164 return init_builtin(name)
165 elif type_ == PY_FROZEN:
166 return init_frozen(name)
167 else:
168 msg = "Don't know how to import {} (type code {}".format(name, type_)
169 raise ImportError(msg, name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400170
171
172def find_module(name, path=None):
173 """Search for a module.
174
175 If path is omitted or None, search for a built-in, frozen or special
176 module and continue search in sys.path. The module name cannot
177 contain '.'; to search for a submodule of a package, pass the
178 submodule name and the package's __path__.
179
180 """
181 if not isinstance(name, str):
182 raise TypeError("'name' must be a str, not {}".format(type(name)))
183 elif not isinstance(path, (type(None), list)):
184 # Backwards-compatibility
185 raise RuntimeError("'list' must be None or a list, "
186 "not {}".format(type(name)))
187
188 if path is None:
189 if is_builtin(name):
190 return None, None, ('', '', C_BUILTIN)
191 elif is_frozen(name):
192 return None, None, ('', '', PY_FROZEN)
193 else:
194 path = sys.path
195
196 for entry in path:
197 package_directory = os.path.join(entry, name)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400198 for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
Brett Cannone69f0df2012-04-21 21:09:46 -0400199 package_file_name = '__init__' + suffix
200 file_path = os.path.join(package_directory, package_file_name)
201 if os.path.isfile(file_path):
202 return None, package_directory, ('', '', PKG_DIRECTORY)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400203 with warnings.catch_warnings():
204 warnings.simplefilter('ignore')
205 for suffix, mode, type_ in get_suffixes():
206 file_name = name + suffix
207 file_path = os.path.join(entry, file_name)
208 if os.path.isfile(file_path):
209 break
210 else:
211 continue
212 break # Break out of outer loop when breaking out of inner loop.
Brett Cannone69f0df2012-04-21 21:09:46 -0400213 else:
214 raise ImportError('No module name {!r}'.format(name), name=name)
215
216 encoding = None
217 if mode == 'U':
218 with open(file_path, 'rb') as file:
219 encoding = tokenize.detect_encoding(file.readline)[0]
220 file = open(file_path, mode, encoding=encoding)
221 return file, file_path, (suffix, mode, type_)
Brett Cannon62228db2012-04-29 14:38:11 -0400222
223
224_RELOADING = {}
225
226def reload(module):
227 """Reload the module and return it.
228
229 The module must have been successfully imported before.
230
231 """
232 if not module or type(module) != type(sys):
233 raise TypeError("reload() argument must be module")
234 name = module.__name__
235 if name not in sys.modules:
236 msg = "module {} not in sys.modules"
237 raise ImportError(msg.format(name), name=name)
238 if name in _RELOADING:
239 return _RELOADING[name]
240 _RELOADING[name] = module
241 try:
242 parent_name = name.rpartition('.')[0]
243 if parent_name and parent_name not in sys.modules:
244 msg = "parent {!r} not in sys.modules"
245 raise ImportError(msg.format(parentname), name=parent_name)
246 return module.__loader__.load_module(name)
247 finally:
248 try:
249 del _RELOADING[name]
250 except KeyError:
251 pass