blob: 717b6a43432a7f35575b2a218daf5256dfe73698 [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
20import os
Brett Cannone69f0df2012-04-21 21:09:46 -040021import sys
22import tokenize
23
24
25# XXX "deprecate" once find_module(), load_module(), and get_suffixes() are
26# deprecated.
27SEARCH_ERROR = 0
28PY_SOURCE = 1
29PY_COMPILED = 2
30C_EXTENSION = 3
31PY_RESOURCE = 4
32PKG_DIRECTORY = 5
33C_BUILTIN = 6
34PY_FROZEN = 7
35PY_CODERESOURCE = 8
36IMP_HOOK = 9
Brett Cannon2ee61422012-04-15 22:28:28 -040037
38
Brett Cannon2657df42012-05-04 15:20:40 -040039def get_suffixes():
40 extensions = [(s, 'rb', C_EXTENSION) for s in extension_suffixes()]
41 source = [(s, 'U', PY_SOURCE) for s in _bootstrap._SOURCE_SUFFIXES]
42 bytecode = [(_bootstrap._BYTECODE_SUFFIX, 'rb', PY_COMPILED)]
43
44 return extensions + source + bytecode
45
46
Brett Cannona64faf02012-04-21 18:52:52 -040047def source_from_cache(path):
48 """Given the path to a .pyc./.pyo file, return the path to its .py file.
49
50 The .pyc/.pyo file does not need to exist; this simply returns the path to
51 the .py file calculated to correspond to the .pyc/.pyo file. If path does
52 not conform to PEP 3147 format, ValueError will be raised.
53
54 """
55 head, pycache_filename = os.path.split(path)
56 head, pycache = os.path.split(head)
Brett Cannon17098a52012-05-04 13:52:49 -040057 if pycache != _bootstrap._PYCACHE:
Brett Cannona64faf02012-04-21 18:52:52 -040058 raise ValueError('{} not bottom-level directory in '
Brett Cannon17098a52012-05-04 13:52:49 -040059 '{!r}'.format(_bootstrap._PYCACHE, path))
Brett Cannona64faf02012-04-21 18:52:52 -040060 if pycache_filename.count('.') != 2:
61 raise ValueError('expected only 2 dots in '
62 '{!r}'.format(pycache_filename))
63 base_filename = pycache_filename.partition('.')[0]
Brett Cannon17098a52012-05-04 13:52:49 -040064 return os.path.join(head, base_filename + _bootstrap._SOURCE_SUFFIXES[0])
Brett Cannona64faf02012-04-21 18:52:52 -040065
66
Brett Cannonacf85cd2012-04-29 12:50:03 -040067class NullImporter:
68
69 """Null import object."""
70
71 def __init__(self, path):
72 if path == '':
73 raise ImportError('empty pathname', path='')
74 elif os.path.isdir(path):
75 raise ImportError('existing directory', path=path)
76
77 def find_module(self, fullname):
78 """Always returns None."""
79 return None
80
81
Brett Cannon64befe92012-04-17 19:14:26 -040082class _HackedGetData:
Brett Cannon16475ad2012-04-16 22:11:25 -040083
Brett Cannon64befe92012-04-17 19:14:26 -040084 """Compatibiilty support for 'file' arguments of various load_*()
85 functions."""
Brett Cannon16475ad2012-04-16 22:11:25 -040086
87 def __init__(self, fullname, path, file=None):
88 super().__init__(fullname, path)
89 self.file = file
90
91 def get_data(self, path):
Brett Cannon64befe92012-04-17 19:14:26 -040092 """Gross hack to contort loader to deal w/ load_*()'s bad API."""
Brett Cannon938d44d2012-04-22 19:58:33 -040093 if self.file and path == self.path:
Brett Cannon16475ad2012-04-16 22:11:25 -040094 with self.file:
95 # Technically should be returning bytes, but
96 # SourceLoader.get_code() just passed what is returned to
97 # compile() which can handle str. And converting to bytes would
98 # require figuring out the encoding to decode to and
99 # tokenize.detect_encoding() only accepts bytes.
100 return self.file.read()
101 else:
102 return super().get_data(path)
103
104
Brett Cannon938d44d2012-04-22 19:58:33 -0400105class _LoadSourceCompatibility(_HackedGetData, _bootstrap.SourceFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400106
107 """Compatibility support for implementing load_source()."""
108
109
Brett Cannona64faf02012-04-21 18:52:52 -0400110# XXX deprecate after better API exposed in importlib
Brett Cannon16475ad2012-04-16 22:11:25 -0400111def load_source(name, pathname, file=None):
112 return _LoadSourceCompatibility(name, pathname, file).load_module(name)
113
114
Brett Cannon64befe92012-04-17 19:14:26 -0400115class _LoadCompiledCompatibility(_HackedGetData,
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200116 _bootstrap.SourcelessFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400117
118 """Compatibility support for implementing load_compiled()."""
119
120
Brett Cannona64faf02012-04-21 18:52:52 -0400121# XXX deprecate
Brett Cannon64befe92012-04-17 19:14:26 -0400122def load_compiled(name, pathname, file=None):
123 return _LoadCompiledCompatibility(name, pathname, file).load_module(name)
124
125
Brett Cannona64faf02012-04-21 18:52:52 -0400126# XXX deprecate
Brett Cannon2ee61422012-04-15 22:28:28 -0400127def load_package(name, path):
128 if os.path.isdir(path):
Benjamin Petersonef5a4632012-05-05 09:44:08 -0400129 extensions = _bootstrap._SOURCE_SUFFIXES + [_bootstrap._BYTECODE_SUFFIX]
Brett Cannon2ee61422012-04-15 22:28:28 -0400130 for extension in extensions:
131 path = os.path.join(path, '__init__'+extension)
132 if os.path.exists(path):
133 break
134 else:
135 raise ValueError('{!r} is not a package'.format(path))
Brett Cannon938d44d2012-04-22 19:58:33 -0400136 return _bootstrap.SourceFileLoader(name, path).load_module(name)
Brett Cannon2ee61422012-04-15 22:28:28 -0400137
Brett Cannon01a76172012-04-15 20:25:23 -0400138
Brett Cannona64faf02012-04-21 18:52:52 -0400139# XXX deprecate
Brett Cannon01a76172012-04-15 20:25:23 -0400140def load_module(name, file, filename, details):
141 """Load a module, given information returned by find_module().
142
143 The module name must include the full package name, if any.
144
145 """
146 suffix, mode, type_ = details
Brett Cannonde10bf42012-04-16 20:44:21 -0400147 if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
Brett Cannon01a76172012-04-15 20:25:23 -0400148 raise ValueError('invalid file open mode {!r}'.format(mode))
149 elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
150 msg = 'file object required for import (type code {})'.format(type_)
151 raise ValueError(msg)
152 elif type_ == PY_SOURCE:
153 return load_source(name, filename, file)
154 elif type_ == PY_COMPILED:
155 return load_compiled(name, filename, file)
156 elif type_ == PKG_DIRECTORY:
157 return load_package(name, filename)
158 elif type_ == C_BUILTIN:
159 return init_builtin(name)
160 elif type_ == PY_FROZEN:
161 return init_frozen(name)
162 else:
163 msg = "Don't know how to import {} (type code {}".format(name, type_)
164 raise ImportError(msg, name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400165
166
167def find_module(name, path=None):
168 """Search for a module.
169
170 If path is omitted or None, search for a built-in, frozen or special
171 module and continue search in sys.path. The module name cannot
172 contain '.'; to search for a submodule of a package, pass the
173 submodule name and the package's __path__.
174
175 """
176 if not isinstance(name, str):
177 raise TypeError("'name' must be a str, not {}".format(type(name)))
178 elif not isinstance(path, (type(None), list)):
179 # Backwards-compatibility
180 raise RuntimeError("'list' must be None or a list, "
181 "not {}".format(type(name)))
182
183 if path is None:
184 if is_builtin(name):
185 return None, None, ('', '', C_BUILTIN)
186 elif is_frozen(name):
187 return None, None, ('', '', PY_FROZEN)
188 else:
189 path = sys.path
190
191 for entry in path:
192 package_directory = os.path.join(entry, name)
Brett Cannon17098a52012-05-04 13:52:49 -0400193 for suffix in ['.py', _bootstrap._BYTECODE_SUFFIX]:
Brett Cannone69f0df2012-04-21 21:09:46 -0400194 package_file_name = '__init__' + suffix
195 file_path = os.path.join(package_directory, package_file_name)
196 if os.path.isfile(file_path):
197 return None, package_directory, ('', '', PKG_DIRECTORY)
198 for suffix, mode, type_ in get_suffixes():
199 file_name = name + suffix
200 file_path = os.path.join(entry, file_name)
201 if os.path.isfile(file_path):
202 break
203 else:
204 continue
205 break # Break out of outer loop when breaking out of inner loop.
206 else:
207 raise ImportError('No module name {!r}'.format(name), name=name)
208
209 encoding = None
210 if mode == 'U':
211 with open(file_path, 'rb') as file:
212 encoding = tokenize.detect_encoding(file.readline)[0]
213 file = open(file_path, mode, encoding=encoding)
214 return file, file_path, (suffix, mode, type_)
Brett Cannon62228db2012-04-29 14:38:11 -0400215
216
217_RELOADING = {}
218
219def reload(module):
220 """Reload the module and return it.
221
222 The module must have been successfully imported before.
223
224 """
225 if not module or type(module) != type(sys):
226 raise TypeError("reload() argument must be module")
227 name = module.__name__
228 if name not in sys.modules:
229 msg = "module {} not in sys.modules"
230 raise ImportError(msg.format(name), name=name)
231 if name in _RELOADING:
232 return _RELOADING[name]
233 _RELOADING[name] = module
234 try:
235 parent_name = name.rpartition('.')[0]
236 if parent_name and parent_name not in sys.modules:
237 msg = "parent {!r} not in sys.modules"
238 raise ImportError(msg.format(parentname), name=parent_name)
239 return module.__loader__.load_module(name)
240 finally:
241 try:
242 del _RELOADING[name]
243 except KeyError:
244 pass