blob: 419f631153ee3c985eb7a06c281087a9f76c839a [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 Cannon6f44d662012-04-15 16:08:47 -040013
Brett Cannon77b2abd2012-07-09 16:09:00 -040014# Directly exposed by this module
Brett Cannon17098a52012-05-04 13:52:49 -040015from importlib._bootstrap import new_module
Brett Cannona6473f92012-07-13 13:57:03 -040016from importlib._bootstrap import cache_from_source, source_from_cache
Brett Cannon01a76172012-04-15 20:25:23 -040017
Brett Cannon77b2abd2012-07-09 16:09:00 -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 Cannon77b2abd2012-07-09 16:09:00 -040040def get_magic():
41 """Return the magic number for .pyc or .pyo files."""
42 return _bootstrap._MAGIC_BYTES
43
44
Brett Cannon98979b82012-07-02 15:13:11 -040045def get_tag():
46 """Return the magic tag for .pyc or .pyo files."""
47 return sys.implementation.cache_tag
48
49
Brett Cannon2657df42012-05-04 15:20:40 -040050def get_suffixes():
Brett Cannoncb66eb02012-05-11 12:58:42 -040051 warnings.warn('imp.get_suffixes() is deprecated; use the constants '
52 'defined on importlib.machinery instead',
53 DeprecationWarning, 2)
Brett Cannon2657df42012-05-04 15:20:40 -040054 extensions = [(s, 'rb', C_EXTENSION) for s in extension_suffixes()]
Brett Cannoncb66eb02012-05-11 12:58:42 -040055 source = [(s, 'U', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
56 bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
Brett Cannon2657df42012-05-04 15:20:40 -040057
58 return extensions + source + bytecode
59
60
Brett Cannonacf85cd2012-04-29 12:50:03 -040061class NullImporter:
62
63 """Null import object."""
64
65 def __init__(self, path):
66 if path == '':
67 raise ImportError('empty pathname', path='')
68 elif os.path.isdir(path):
69 raise ImportError('existing directory', path=path)
70
71 def find_module(self, fullname):
72 """Always returns None."""
73 return None
74
75
Brett Cannon64befe92012-04-17 19:14:26 -040076class _HackedGetData:
Brett Cannon16475ad2012-04-16 22:11:25 -040077
Brett Cannon64befe92012-04-17 19:14:26 -040078 """Compatibiilty support for 'file' arguments of various load_*()
79 functions."""
Brett Cannon16475ad2012-04-16 22:11:25 -040080
81 def __init__(self, fullname, path, file=None):
82 super().__init__(fullname, path)
83 self.file = file
84
85 def get_data(self, path):
Brett Cannon64befe92012-04-17 19:14:26 -040086 """Gross hack to contort loader to deal w/ load_*()'s bad API."""
Brett Cannon938d44d2012-04-22 19:58:33 -040087 if self.file and path == self.path:
Brett Cannon16475ad2012-04-16 22:11:25 -040088 with self.file:
89 # Technically should be returning bytes, but
90 # SourceLoader.get_code() just passed what is returned to
91 # compile() which can handle str. And converting to bytes would
92 # require figuring out the encoding to decode to and
93 # tokenize.detect_encoding() only accepts bytes.
94 return self.file.read()
95 else:
96 return super().get_data(path)
97
98
Brett Cannon938d44d2012-04-22 19:58:33 -040099class _LoadSourceCompatibility(_HackedGetData, _bootstrap.SourceFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400100
101 """Compatibility support for implementing load_source()."""
102
103
Brett Cannon16475ad2012-04-16 22:11:25 -0400104def load_source(name, pathname, file=None):
Brett Cannonc0499522012-05-11 14:48:41 -0400105 msg = ('imp.load_source() is deprecated; use '
106 'importlib.machinery.SourceFileLoader(name, pathname).load_module()'
107 ' instead')
108 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon16475ad2012-04-16 22:11:25 -0400109 return _LoadSourceCompatibility(name, pathname, file).load_module(name)
110
111
Brett Cannon64befe92012-04-17 19:14:26 -0400112class _LoadCompiledCompatibility(_HackedGetData,
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200113 _bootstrap.SourcelessFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400114
115 """Compatibility support for implementing load_compiled()."""
116
117
118def load_compiled(name, pathname, file=None):
Brett Cannonc0499522012-05-11 14:48:41 -0400119 msg = ('imp.load_compiled() is deprecated; use '
120 'importlib.machinery.SourcelessFileLoader(name, pathname).'
121 'load_module() instead ')
122 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon64befe92012-04-17 19:14:26 -0400123 return _LoadCompiledCompatibility(name, pathname, file).load_module(name)
124
125
Brett Cannon2ee61422012-04-15 22:28:28 -0400126def load_package(name, path):
Brett Cannonc0499522012-05-11 14:48:41 -0400127 msg = ('imp.load_package() is deprecated; use either '
128 'importlib.machinery.SourceFileLoader() or '
129 'importlib.machinery.SourcelessFileLoader() instead')
130 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon2ee61422012-04-15 22:28:28 -0400131 if os.path.isdir(path):
Brett Cannonc0499522012-05-11 14:48:41 -0400132 extensions = (machinery.SOURCE_SUFFIXES[:] +
133 machinery.BYTECODE_SUFFIXES[:])
Brett Cannon2ee61422012-04-15 22:28:28 -0400134 for extension in extensions:
135 path = os.path.join(path, '__init__'+extension)
136 if os.path.exists(path):
137 break
138 else:
139 raise ValueError('{!r} is not a package'.format(path))
Brett Cannon938d44d2012-04-22 19:58:33 -0400140 return _bootstrap.SourceFileLoader(name, path).load_module(name)
Brett Cannon2ee61422012-04-15 22:28:28 -0400141
Brett Cannon01a76172012-04-15 20:25:23 -0400142
143def load_module(name, file, filename, details):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400144 """**DEPRECATED**
145
146 Load a module, given information returned by find_module().
Brett Cannon01a76172012-04-15 20:25:23 -0400147
148 The module name must include the full package name, if any.
149
150 """
151 suffix, mode, type_ = details
Brett Cannonc0499522012-05-11 14:48:41 -0400152 with warnings.catch_warnings():
153 warnings.simplefilter('ignore')
154 if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
155 raise ValueError('invalid file open mode {!r}'.format(mode))
156 elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
157 msg = 'file object required for import (type code {})'.format(type_)
158 raise ValueError(msg)
159 elif type_ == PY_SOURCE:
160 return load_source(name, filename, file)
161 elif type_ == PY_COMPILED:
162 return load_compiled(name, filename, file)
163 elif type_ == PKG_DIRECTORY:
164 return load_package(name, filename)
165 elif type_ == C_BUILTIN:
166 return init_builtin(name)
167 elif type_ == PY_FROZEN:
168 return init_frozen(name)
169 else:
170 msg = "Don't know how to import {} (type code {}".format(name, type_)
171 raise ImportError(msg, name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400172
173
174def find_module(name, path=None):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400175 """**DEPRECATED**
176
177 Search for a module.
Brett Cannone69f0df2012-04-21 21:09:46 -0400178
179 If path is omitted or None, search for a built-in, frozen or special
180 module and continue search in sys.path. The module name cannot
181 contain '.'; to search for a submodule of a package, pass the
182 submodule name and the package's __path__.
183
184 """
185 if not isinstance(name, str):
186 raise TypeError("'name' must be a str, not {}".format(type(name)))
187 elif not isinstance(path, (type(None), list)):
188 # Backwards-compatibility
189 raise RuntimeError("'list' must be None or a list, "
190 "not {}".format(type(name)))
191
192 if path is None:
193 if is_builtin(name):
194 return None, None, ('', '', C_BUILTIN)
195 elif is_frozen(name):
196 return None, None, ('', '', PY_FROZEN)
197 else:
198 path = sys.path
199
200 for entry in path:
201 package_directory = os.path.join(entry, name)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400202 for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
Brett Cannone69f0df2012-04-21 21:09:46 -0400203 package_file_name = '__init__' + suffix
204 file_path = os.path.join(package_directory, package_file_name)
205 if os.path.isfile(file_path):
206 return None, package_directory, ('', '', PKG_DIRECTORY)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400207 with warnings.catch_warnings():
208 warnings.simplefilter('ignore')
209 for suffix, mode, type_ in get_suffixes():
210 file_name = name + suffix
211 file_path = os.path.join(entry, file_name)
212 if os.path.isfile(file_path):
213 break
214 else:
215 continue
216 break # Break out of outer loop when breaking out of inner loop.
Brett Cannone69f0df2012-04-21 21:09:46 -0400217 else:
Brett Cannonbf7eab02012-07-09 13:24:34 -0400218 raise ImportError(_bootstrap._ERR_MSG.format(name), name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400219
220 encoding = None
221 if mode == 'U':
222 with open(file_path, 'rb') as file:
223 encoding = tokenize.detect_encoding(file.readline)[0]
224 file = open(file_path, mode, encoding=encoding)
225 return file, file_path, (suffix, mode, type_)
Brett Cannon62228db2012-04-29 14:38:11 -0400226
227
228_RELOADING = {}
229
230def reload(module):
231 """Reload the module and return it.
232
233 The module must have been successfully imported before.
234
235 """
236 if not module or type(module) != type(sys):
237 raise TypeError("reload() argument must be module")
238 name = module.__name__
239 if name not in sys.modules:
240 msg = "module {} not in sys.modules"
241 raise ImportError(msg.format(name), name=name)
242 if name in _RELOADING:
243 return _RELOADING[name]
244 _RELOADING[name] = module
245 try:
246 parent_name = name.rpartition('.')[0]
247 if parent_name and parent_name not in sys.modules:
248 msg = "parent {!r} not in sys.modules"
249 raise ImportError(msg.format(parentname), name=parent_name)
250 return module.__loader__.load_module(name)
251 finally:
252 try:
253 del _RELOADING[name]
254 except KeyError:
255 pass