blob: 2abd7af0dba82a56764056ccda6662ca747b4dae [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
9from _imp import (lock_held, acquire_lock, release_lock, reload,
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,
12 _fix_co_filename)
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 Cannonea59dbf2012-04-20 21:44:46 -040015# Can (probably) move to importlib
Brett Cannon2f923892012-04-21 18:55:51 -040016from _imp import get_suffixes
Brett Cannon6f44d662012-04-15 16:08:47 -040017
18from importlib._bootstrap import _new_module as new_module
Brett Cannonea59dbf2012-04-20 21:44:46 -040019from importlib._bootstrap import _cache_from_source as cache_from_source
Brett Cannon01a76172012-04-15 20:25:23 -040020
Brett Cannon2ee61422012-04-15 22:28:28 -040021from importlib import _bootstrap
22import os
Brett Cannone69f0df2012-04-21 21:09:46 -040023import sys
24import tokenize
25
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 Cannona64faf02012-04-21 18:52:52 -040041def source_from_cache(path):
42 """Given the path to a .pyc./.pyo file, return the path to its .py file.
43
44 The .pyc/.pyo file does not need to exist; this simply returns the path to
45 the .py file calculated to correspond to the .pyc/.pyo file. If path does
46 not conform to PEP 3147 format, ValueError will be raised.
47
48 """
49 head, pycache_filename = os.path.split(path)
50 head, pycache = os.path.split(head)
51 if pycache != _bootstrap.PYCACHE:
52 raise ValueError('{} not bottom-level directory in '
53 '{!r}'.format(_bootstrap.PYCACHE, path))
54 if pycache_filename.count('.') != 2:
55 raise ValueError('expected only 2 dots in '
56 '{!r}'.format(pycache_filename))
57 base_filename = pycache_filename.partition('.')[0]
58 return os.path.join(head, base_filename + _bootstrap.SOURCE_SUFFIXES[0])
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 Cannona64faf02012-04-21 18:52:52 -0400104# XXX deprecate after better API exposed in importlib
Brett Cannon16475ad2012-04-16 22:11:25 -0400105def load_source(name, pathname, file=None):
106 return _LoadSourceCompatibility(name, pathname, file).load_module(name)
107
108
Brett Cannon64befe92012-04-17 19:14:26 -0400109class _LoadCompiledCompatibility(_HackedGetData,
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200110 _bootstrap.SourcelessFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400111
112 """Compatibility support for implementing load_compiled()."""
113
114
Brett Cannona64faf02012-04-21 18:52:52 -0400115# XXX deprecate
Brett Cannon64befe92012-04-17 19:14:26 -0400116def load_compiled(name, pathname, file=None):
117 return _LoadCompiledCompatibility(name, pathname, file).load_module(name)
118
119
Brett Cannona64faf02012-04-21 18:52:52 -0400120# XXX deprecate
Brett Cannon2ee61422012-04-15 22:28:28 -0400121def load_package(name, path):
122 if os.path.isdir(path):
123 extensions = _bootstrap._suffix_list(PY_SOURCE)
124 extensions += _bootstrap._suffix_list(PY_COMPILED)
125 for extension in extensions:
126 path = os.path.join(path, '__init__'+extension)
127 if os.path.exists(path):
128 break
129 else:
130 raise ValueError('{!r} is not a package'.format(path))
Brett Cannon938d44d2012-04-22 19:58:33 -0400131 return _bootstrap.SourceFileLoader(name, path).load_module(name)
Brett Cannon2ee61422012-04-15 22:28:28 -0400132
Brett Cannon01a76172012-04-15 20:25:23 -0400133
Brett Cannona64faf02012-04-21 18:52:52 -0400134# XXX deprecate
Brett Cannon01a76172012-04-15 20:25:23 -0400135def load_module(name, file, filename, details):
136 """Load a module, given information returned by find_module().
137
138 The module name must include the full package name, if any.
139
140 """
141 suffix, mode, type_ = details
Brett Cannonde10bf42012-04-16 20:44:21 -0400142 if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
Brett Cannon01a76172012-04-15 20:25:23 -0400143 raise ValueError('invalid file open mode {!r}'.format(mode))
144 elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
145 msg = 'file object required for import (type code {})'.format(type_)
146 raise ValueError(msg)
147 elif type_ == PY_SOURCE:
148 return load_source(name, filename, file)
149 elif type_ == PY_COMPILED:
150 return load_compiled(name, filename, file)
151 elif type_ == PKG_DIRECTORY:
152 return load_package(name, filename)
153 elif type_ == C_BUILTIN:
154 return init_builtin(name)
155 elif type_ == PY_FROZEN:
156 return init_frozen(name)
157 else:
158 msg = "Don't know how to import {} (type code {}".format(name, type_)
159 raise ImportError(msg, name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400160
161
162def find_module(name, path=None):
163 """Search for a module.
164
165 If path is omitted or None, search for a built-in, frozen or special
166 module and continue search in sys.path. The module name cannot
167 contain '.'; to search for a submodule of a package, pass the
168 submodule name and the package's __path__.
169
170 """
171 if not isinstance(name, str):
172 raise TypeError("'name' must be a str, not {}".format(type(name)))
173 elif not isinstance(path, (type(None), list)):
174 # Backwards-compatibility
175 raise RuntimeError("'list' must be None or a list, "
176 "not {}".format(type(name)))
177
178 if path is None:
179 if is_builtin(name):
180 return None, None, ('', '', C_BUILTIN)
181 elif is_frozen(name):
182 return None, None, ('', '', PY_FROZEN)
183 else:
184 path = sys.path
185
186 for entry in path:
187 package_directory = os.path.join(entry, name)
188 for suffix in ['.py', _bootstrap.BYTECODE_SUFFIX]:
189 package_file_name = '__init__' + suffix
190 file_path = os.path.join(package_directory, package_file_name)
191 if os.path.isfile(file_path):
192 return None, package_directory, ('', '', PKG_DIRECTORY)
193 for suffix, mode, type_ in get_suffixes():
194 file_name = name + suffix
195 file_path = os.path.join(entry, file_name)
196 if os.path.isfile(file_path):
197 break
198 else:
199 continue
200 break # Break out of outer loop when breaking out of inner loop.
201 else:
202 raise ImportError('No module name {!r}'.format(name), name=name)
203
204 encoding = None
205 if mode == 'U':
206 with open(file_path, 'rb') as file:
207 encoding = tokenize.detect_encoding(file.readline)[0]
208 file = open(file_path, mode, encoding=encoding)
209 return file, file_path, (suffix, mode, type_)