Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 1 | """Core implementation of import. |
| 2 | |
| 3 | This module is NOT meant to be directly imported! It has been designed such |
| 4 | that it can be bootstrapped into Python as the implementation of import. As |
| 5 | such it requires the injection of specific modules and attributes in order to |
| 6 | work. One should use importlib as the public-facing version of this module. |
| 7 | |
| 8 | """ |
Marc-Andre Lemburg | 7541c8e | 2012-04-25 10:54:48 +0200 | [diff] [blame] | 9 | # |
| 10 | # IMPORTANT: Whenever making changes to this module, be sure to run |
| 11 | # a top-level make in order to get the frozen version of the module |
| 12 | # update. Not doing so, will result in the Makefile to fail for |
| 13 | # all others who don't have a ./python around to freeze the module |
| 14 | # in the early stages of compilation. |
| 15 | # |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 16 | |
Brett Cannon | ed672d6 | 2012-04-20 21:19:53 -0400 | [diff] [blame] | 17 | # See importlib._setup() for what is injected into the global namespace. |
| 18 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 19 | # When editing this code be aware that code executed at import time CANNOT |
| 20 | # reference any injected objects! This includes not only global code but also |
| 21 | # anything specified at the class level. |
| 22 | |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 23 | # XXX Make sure all public names have no single leading underscore and all |
| 24 | # others do. |
| 25 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 26 | |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 27 | # Bootstrap-related code ###################################################### |
| 28 | |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 29 | _CASE_INSENSITIVE_PLATFORMS = 'win', 'cygwin', 'darwin' |
Brett Cannon | 51d14f8 | 2012-01-26 19:03:52 -0500 | [diff] [blame] | 30 | |
Brett Cannon | 51d14f8 | 2012-01-26 19:03:52 -0500 | [diff] [blame] | 31 | |
Antoine Pitrou | b67075b | 2012-02-20 13:52:47 +0100 | [diff] [blame] | 32 | def _make_relax_case(): |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 33 | if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS): |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 34 | def _relax_case(): |
Benjamin Peterson | 6ddac00 | 2012-02-20 15:06:35 -0500 | [diff] [blame] | 35 | """True if filenames must be checked case-insensitively.""" |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 36 | return b'PYTHONCASEOK' in _os.environ |
Brett Cannon | 51d14f8 | 2012-01-26 19:03:52 -0500 | [diff] [blame] | 37 | else: |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 38 | def _relax_case(): |
Benjamin Peterson | 6ddac00 | 2012-02-20 15:06:35 -0500 | [diff] [blame] | 39 | """True if filenames must be checked case-insensitively.""" |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 40 | return False |
| 41 | return _relax_case |
Brett Cannon | 51d14f8 | 2012-01-26 19:03:52 -0500 | [diff] [blame] | 42 | |
| 43 | |
Brett Cannon | c264e3e | 2012-01-25 18:58:03 -0500 | [diff] [blame] | 44 | # TODO: Expose from marshal |
| 45 | def _w_long(x): |
| 46 | """Convert a 32-bit integer to little-endian. |
| 47 | |
| 48 | XXX Temporary until marshal's long functions are exposed. |
| 49 | |
| 50 | """ |
Brett Cannon | c190389 | 2013-02-25 17:10:11 -0500 | [diff] [blame] | 51 | return (int(x) & 0xFFFFFFFF).to_bytes(4, 'little') |
Brett Cannon | c264e3e | 2012-01-25 18:58:03 -0500 | [diff] [blame] | 52 | |
| 53 | |
| 54 | # TODO: Expose from marshal |
| 55 | def _r_long(int_bytes): |
| 56 | """Convert 4 bytes in little-endian to an integer. |
| 57 | |
| 58 | XXX Temporary until marshal's long function are exposed. |
| 59 | |
| 60 | """ |
Serhiy Storchaka | 39e47f9 | 2013-02-25 15:40:33 +0200 | [diff] [blame] | 61 | return int.from_bytes(int_bytes, 'little') |
Brett Cannon | c264e3e | 2012-01-25 18:58:03 -0500 | [diff] [blame] | 62 | |
| 63 | |
Brett Cannon | 5c903e6 | 2012-04-22 11:45:07 -0400 | [diff] [blame] | 64 | def _path_join(*path_parts): |
Brett Cannon | ed672d6 | 2012-04-20 21:19:53 -0400 | [diff] [blame] | 65 | """Replacement for os.path.join().""" |
Serhiy Storchaka | 39e47f9 | 2013-02-25 15:40:33 +0200 | [diff] [blame] | 66 | return path_sep.join([part.rstrip(path_separators) |
| 67 | for part in path_parts if part]) |
Brett Cannon | ed672d6 | 2012-04-20 21:19:53 -0400 | [diff] [blame] | 68 | |
| 69 | |
| 70 | def _path_split(path): |
| 71 | """Replacement for os.path.split().""" |
Serhiy Storchaka | 39e47f9 | 2013-02-25 15:40:33 +0200 | [diff] [blame] | 72 | if len(path_separators) == 1: |
| 73 | front, _, tail = path.rpartition(path_sep) |
| 74 | return front, tail |
Brett Cannon | ed672d6 | 2012-04-20 21:19:53 -0400 | [diff] [blame] | 75 | for x in reversed(path): |
| 76 | if x in path_separators: |
Brett Cannon | c190389 | 2013-02-25 17:10:11 -0500 | [diff] [blame] | 77 | front, tail = path.rsplit(x, maxsplit=1) |
Serhiy Storchaka | 39e47f9 | 2013-02-25 15:40:33 +0200 | [diff] [blame] | 78 | return front, tail |
| 79 | return '', path |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 80 | |
| 81 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 82 | def _path_is_mode_type(path, mode): |
| 83 | """Test whether the path is the specified mode type.""" |
| 84 | try: |
| 85 | stat_info = _os.stat(path) |
| 86 | except OSError: |
| 87 | return False |
| 88 | return (stat_info.st_mode & 0o170000) == mode |
| 89 | |
| 90 | |
| 91 | # XXX Could also expose Modules/getpath.c:isfile() |
| 92 | def _path_isfile(path): |
| 93 | """Replacement for os.path.isfile.""" |
| 94 | return _path_is_mode_type(path, 0o100000) |
| 95 | |
| 96 | |
| 97 | # XXX Could also expose Modules/getpath.c:isdir() |
| 98 | def _path_isdir(path): |
| 99 | """Replacement for os.path.isdir.""" |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 100 | if not path: |
| 101 | path = _os.getcwd() |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 102 | return _path_is_mode_type(path, 0o040000) |
| 103 | |
| 104 | |
Nick Coghlan | a508770 | 2012-08-24 18:32:40 +1000 | [diff] [blame] | 105 | def _write_atomic(path, data, mode=0o666): |
Charles-François Natali | 6db1c40 | 2012-02-22 21:03:09 +0100 | [diff] [blame] | 106 | """Best-effort function to write data to a path atomically. |
| 107 | Be prepared to handle a FileExistsError if concurrent writing of the |
| 108 | temporary file is attempted.""" |
Antoine Pitrou | 28e401e | 2011-11-15 19:15:19 +0100 | [diff] [blame] | 109 | # id() is used to generate a pseudo-random filename. |
| 110 | path_tmp = '{}.{}'.format(path, id(path)) |
Nick Coghlan | a508770 | 2012-08-24 18:32:40 +1000 | [diff] [blame] | 111 | fd = _os.open(path_tmp, |
| 112 | _os.O_EXCL | _os.O_CREAT | _os.O_WRONLY, mode & 0o666) |
Antoine Pitrou | 28e401e | 2011-11-15 19:15:19 +0100 | [diff] [blame] | 113 | try: |
Brett Cannon | ba17fe2 | 2012-02-17 09:26:53 -0500 | [diff] [blame] | 114 | # We first write data to a temporary file, and then use os.replace() to |
| 115 | # perform an atomic rename. |
Antoine Pitrou | 28e401e | 2011-11-15 19:15:19 +0100 | [diff] [blame] | 116 | with _io.FileIO(fd, 'wb') as file: |
Antoine Pitrou | 707033a | 2011-10-17 19:28:44 +0200 | [diff] [blame] | 117 | file.write(data) |
Brett Cannon | ba17fe2 | 2012-02-17 09:26:53 -0500 | [diff] [blame] | 118 | _os.replace(path_tmp, path) |
Antoine Pitrou | 28e401e | 2011-11-15 19:15:19 +0100 | [diff] [blame] | 119 | except OSError: |
| 120 | try: |
| 121 | _os.unlink(path_tmp) |
| 122 | except OSError: |
| 123 | pass |
| 124 | raise |
Antoine Pitrou | 707033a | 2011-10-17 19:28:44 +0200 | [diff] [blame] | 125 | |
| 126 | |
Brett Cannon | 3eeaa0a | 2009-03-12 22:07:17 +0000 | [diff] [blame] | 127 | def _wrap(new, old): |
Florent Xicluna | 79d79a0 | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 128 | """Simple substitute for functools.update_wrapper.""" |
Meador Inge | 96ff084 | 2011-12-14 22:53:13 -0600 | [diff] [blame] | 129 | for replace in ['__module__', '__name__', '__qualname__', '__doc__']: |
Brett Cannon | 8490fab | 2012-02-08 18:44:14 -0500 | [diff] [blame] | 130 | if hasattr(old, replace): |
| 131 | setattr(new, replace, getattr(old, replace)) |
Brett Cannon | 51d8bfc | 2009-02-07 02:13:28 +0000 | [diff] [blame] | 132 | new.__dict__.update(old.__dict__) |
| 133 | |
| 134 | |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 135 | _code_type = type(_wrap.__code__) |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 136 | |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 137 | |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 138 | def new_module(name): |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 139 | """Create a new module. |
| 140 | |
| 141 | The module is not entered into sys.modules. |
| 142 | |
| 143 | """ |
Brett Cannon | f19c191 | 2012-05-04 15:46:04 -0400 | [diff] [blame] | 144 | return type(_io)(name) |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 145 | |
| 146 | |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 147 | # Module-level locking ######################################################## |
| 148 | |
| 149 | # A dict mapping module names to weakrefs of _ModuleLock instances |
| 150 | _module_locks = {} |
| 151 | # A dict mapping thread ids to _ModuleLock instances |
| 152 | _blocking_on = {} |
| 153 | |
| 154 | |
| 155 | class _DeadlockError(RuntimeError): |
| 156 | pass |
| 157 | |
| 158 | |
| 159 | class _ModuleLock: |
| 160 | """A recursive lock implementation which is able to detect deadlocks |
| 161 | (e.g. thread 1 trying to take locks A then B, and thread 2 trying to |
| 162 | take locks B then A). |
| 163 | """ |
| 164 | |
| 165 | def __init__(self, name): |
| 166 | self.lock = _thread.allocate_lock() |
| 167 | self.wakeup = _thread.allocate_lock() |
| 168 | self.name = name |
| 169 | self.owner = None |
| 170 | self.count = 0 |
| 171 | self.waiters = 0 |
| 172 | |
| 173 | def has_deadlock(self): |
| 174 | # Deadlock avoidance for concurrent circular imports. |
| 175 | me = _thread.get_ident() |
| 176 | tid = self.owner |
| 177 | while True: |
| 178 | lock = _blocking_on.get(tid) |
| 179 | if lock is None: |
| 180 | return False |
| 181 | tid = lock.owner |
| 182 | if tid == me: |
| 183 | return True |
| 184 | |
| 185 | def acquire(self): |
| 186 | """ |
| 187 | Acquire the module lock. If a potential deadlock is detected, |
| 188 | a _DeadlockError is raised. |
| 189 | Otherwise, the lock is always acquired and True is returned. |
| 190 | """ |
| 191 | tid = _thread.get_ident() |
| 192 | _blocking_on[tid] = self |
| 193 | try: |
| 194 | while True: |
| 195 | with self.lock: |
| 196 | if self.count == 0 or self.owner == tid: |
| 197 | self.owner = tid |
| 198 | self.count += 1 |
| 199 | return True |
| 200 | if self.has_deadlock(): |
| 201 | raise _DeadlockError("deadlock detected by %r" % self) |
| 202 | if self.wakeup.acquire(False): |
| 203 | self.waiters += 1 |
| 204 | # Wait for a release() call |
| 205 | self.wakeup.acquire() |
| 206 | self.wakeup.release() |
| 207 | finally: |
| 208 | del _blocking_on[tid] |
| 209 | |
| 210 | def release(self): |
| 211 | tid = _thread.get_ident() |
| 212 | with self.lock: |
| 213 | if self.owner != tid: |
| 214 | raise RuntimeError("cannot release un-acquired lock") |
| 215 | assert self.count > 0 |
| 216 | self.count -= 1 |
| 217 | if self.count == 0: |
| 218 | self.owner = None |
| 219 | if self.waiters: |
| 220 | self.waiters -= 1 |
| 221 | self.wakeup.release() |
| 222 | |
| 223 | def __repr__(self): |
Brett Cannon | 6072e0b | 2012-10-12 10:00:34 -0400 | [diff] [blame] | 224 | return "_ModuleLock({!r}) at {}".format(self.name, id(self)) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 225 | |
| 226 | |
| 227 | class _DummyModuleLock: |
| 228 | """A simple _ModuleLock equivalent for Python builds without |
| 229 | multi-threading support.""" |
| 230 | |
| 231 | def __init__(self, name): |
| 232 | self.name = name |
| 233 | self.count = 0 |
| 234 | |
| 235 | def acquire(self): |
| 236 | self.count += 1 |
| 237 | return True |
| 238 | |
| 239 | def release(self): |
| 240 | if self.count == 0: |
| 241 | raise RuntimeError("cannot release un-acquired lock") |
| 242 | self.count -= 1 |
| 243 | |
| 244 | def __repr__(self): |
Brett Cannon | 6072e0b | 2012-10-12 10:00:34 -0400 | [diff] [blame] | 245 | return "_DummyModuleLock({!r}) at {}".format(self.name, id(self)) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 246 | |
| 247 | |
| 248 | # The following two functions are for consumption by Python/import.c. |
| 249 | |
| 250 | def _get_module_lock(name): |
| 251 | """Get or create the module lock for a given module name. |
| 252 | |
| 253 | Should only be called with the import lock taken.""" |
| 254 | lock = None |
Antoine Pitrou | 4f0338c | 2012-08-28 00:24:52 +0200 | [diff] [blame] | 255 | try: |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 256 | lock = _module_locks[name]() |
Antoine Pitrou | 4f0338c | 2012-08-28 00:24:52 +0200 | [diff] [blame] | 257 | except KeyError: |
| 258 | pass |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 259 | if lock is None: |
| 260 | if _thread is None: |
| 261 | lock = _DummyModuleLock(name) |
| 262 | else: |
| 263 | lock = _ModuleLock(name) |
| 264 | def cb(_): |
| 265 | del _module_locks[name] |
| 266 | _module_locks[name] = _weakref.ref(lock, cb) |
| 267 | return lock |
| 268 | |
| 269 | def _lock_unlock_module(name): |
| 270 | """Release the global import lock, and acquires then release the |
| 271 | module lock for a given module name. |
| 272 | This is used to ensure a module is completely initialized, in the |
| 273 | event it is being imported by another thread. |
| 274 | |
| 275 | Should only be called with the import lock taken.""" |
| 276 | lock = _get_module_lock(name) |
| 277 | _imp.release_lock() |
| 278 | try: |
| 279 | lock.acquire() |
| 280 | except _DeadlockError: |
| 281 | # Concurrent circular import, we'll accept a partially initialized |
| 282 | # module object. |
| 283 | pass |
| 284 | else: |
| 285 | lock.release() |
| 286 | |
Nick Coghlan | 42c0766 | 2012-07-31 21:14:18 +1000 | [diff] [blame] | 287 | # Frame stripping magic ############################################### |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 288 | |
Nick Coghlan | 42c0766 | 2012-07-31 21:14:18 +1000 | [diff] [blame] | 289 | def _call_with_frames_removed(f, *args, **kwds): |
| 290 | """remove_importlib_frames in import.c will always remove sequences |
| 291 | of importlib frames that end with a call to this function |
| 292 | |
| 293 | Use it instead of a normal call in places where including the importlib |
| 294 | frames introduces unwanted noise into the traceback (e.g. when executing |
| 295 | module code) |
| 296 | """ |
| 297 | return f(*args, **kwds) |
| 298 | |
| 299 | |
| 300 | # Finder/loader utility code ############################################### |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 301 | |
Victor Stinner | 765531d | 2013-03-26 01:11:54 +0100 | [diff] [blame] | 302 | # Magic word to reject .pyc files generated by other Python versions. |
| 303 | # It should change for each incompatible change to the bytecode. |
| 304 | # |
| 305 | # The value of CR and LF is incorporated so if you ever read or write |
| 306 | # a .pyc file in text mode the magic number will be wrong; also, the |
| 307 | # Apple MPW compiler swaps their values, botching string constants. |
| 308 | # |
| 309 | # The magic numbers must be spaced apart at least 2 values, as the |
| 310 | # -U interpeter flag will cause MAGIC+1 being used. They have been |
| 311 | # odd numbers for some time now. |
| 312 | # |
| 313 | # There were a variety of old schemes for setting the magic number. |
| 314 | # The current working scheme is to increment the previous value by |
| 315 | # 10. |
| 316 | # |
| 317 | # Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic |
| 318 | # number also includes a new "magic tag", i.e. a human readable string used |
| 319 | # to represent the magic number in __pycache__ directories. When you change |
| 320 | # the magic number, you must also set a new unique magic tag. Generally this |
| 321 | # can be named after the Python major version of the magic number bump, but |
| 322 | # it can really be anything, as long as it's different than anything else |
| 323 | # that's come before. The tags are included in the following table, starting |
| 324 | # with Python 3.2a0. |
| 325 | # |
| 326 | # Known values: |
| 327 | # Python 1.5: 20121 |
| 328 | # Python 1.5.1: 20121 |
| 329 | # Python 1.5.2: 20121 |
| 330 | # Python 1.6: 50428 |
| 331 | # Python 2.0: 50823 |
| 332 | # Python 2.0.1: 50823 |
| 333 | # Python 2.1: 60202 |
| 334 | # Python 2.1.1: 60202 |
| 335 | # Python 2.1.2: 60202 |
| 336 | # Python 2.2: 60717 |
| 337 | # Python 2.3a0: 62011 |
| 338 | # Python 2.3a0: 62021 |
| 339 | # Python 2.3a0: 62011 (!) |
| 340 | # Python 2.4a0: 62041 |
| 341 | # Python 2.4a3: 62051 |
| 342 | # Python 2.4b1: 62061 |
| 343 | # Python 2.5a0: 62071 |
| 344 | # Python 2.5a0: 62081 (ast-branch) |
| 345 | # Python 2.5a0: 62091 (with) |
| 346 | # Python 2.5a0: 62092 (changed WITH_CLEANUP opcode) |
| 347 | # Python 2.5b3: 62101 (fix wrong code: for x, in ...) |
| 348 | # Python 2.5b3: 62111 (fix wrong code: x += yield) |
| 349 | # Python 2.5c1: 62121 (fix wrong lnotab with for loops and |
| 350 | # storing constants that should have been removed) |
| 351 | # Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp) |
| 352 | # Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode) |
| 353 | # Python 2.6a1: 62161 (WITH_CLEANUP optimization) |
| 354 | # Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND) |
| 355 | # Python 2.7a0: 62181 (optimize conditional branches: |
| 356 | # introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE) |
| 357 | # Python 2.7a0 62191 (introduce SETUP_WITH) |
| 358 | # Python 2.7a0 62201 (introduce BUILD_SET) |
| 359 | # Python 2.7a0 62211 (introduce MAP_ADD and SET_ADD) |
| 360 | # Python 3000: 3000 |
| 361 | # 3010 (removed UNARY_CONVERT) |
| 362 | # 3020 (added BUILD_SET) |
| 363 | # 3030 (added keyword-only parameters) |
| 364 | # 3040 (added signature annotations) |
| 365 | # 3050 (print becomes a function) |
| 366 | # 3060 (PEP 3115 metaclass syntax) |
| 367 | # 3061 (string literals become unicode) |
| 368 | # 3071 (PEP 3109 raise changes) |
| 369 | # 3081 (PEP 3137 make __file__ and __name__ unicode) |
| 370 | # 3091 (kill str8 interning) |
| 371 | # 3101 (merge from 2.6a0, see 62151) |
| 372 | # 3103 (__file__ points to source file) |
| 373 | # Python 3.0a4: 3111 (WITH_CLEANUP optimization). |
| 374 | # Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT) |
| 375 | # Python 3.1a0: 3141 (optimize list, set and dict comprehensions: |
| 376 | # change LIST_APPEND and SET_ADD, add MAP_ADD) |
| 377 | # Python 3.1a0: 3151 (optimize conditional branches: |
| 378 | # introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE) |
| 379 | # Python 3.2a0: 3160 (add SETUP_WITH) |
| 380 | # tag: cpython-32 |
| 381 | # Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR) |
| 382 | # tag: cpython-32 |
| 383 | # Python 3.2a2 3180 (add DELETE_DEREF) |
| 384 | # Python 3.3a0 3190 __class__ super closure changed |
| 385 | # Python 3.3a0 3200 (__qualname__ added) |
| 386 | # 3210 (added size modulo 2**32 to the pyc header) |
| 387 | # Python 3.3a1 3220 (changed PEP 380 implementation) |
| 388 | # Python 3.3a4 3230 (revert changes to implicit __class__ closure) |
| 389 | # Python 3.4a1 3250 (evaluate positional default arguments before |
| 390 | # keyword-only defaults) |
| 391 | # |
| 392 | # MAGIC must change whenever the bytecode emitted by the compiler may no |
| 393 | # longer be understood by older implementations of the eval loop (usually |
| 394 | # due to the addition of new opcodes). |
Brett Cannon | 77b2abd | 2012-07-09 16:09:00 -0400 | [diff] [blame] | 395 | |
Serhiy Storchaka | 39e47f9 | 2013-02-25 15:40:33 +0200 | [diff] [blame] | 396 | _MAGIC_BYTES = (3250).to_bytes(2, 'little') + b'\r\n' |
| 397 | _RAW_MAGIC_NUMBER = int.from_bytes(_MAGIC_BYTES, 'little') |
Brett Cannon | 77b2abd | 2012-07-09 16:09:00 -0400 | [diff] [blame] | 398 | |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 399 | _PYCACHE = '__pycache__' |
Brett Cannon | ea59dbf | 2012-04-20 21:44:46 -0400 | [diff] [blame] | 400 | |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 401 | SOURCE_SUFFIXES = ['.py'] # _setup() adds .pyw as needed. |
Brett Cannon | a64faf0 | 2012-04-21 18:52:52 -0400 | [diff] [blame] | 402 | |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 403 | DEBUG_BYTECODE_SUFFIXES = ['.pyc'] |
| 404 | OPTIMIZED_BYTECODE_SUFFIXES = ['.pyo'] |
Brett Cannon | ea59dbf | 2012-04-20 21:44:46 -0400 | [diff] [blame] | 405 | |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 406 | def cache_from_source(path, debug_override=None): |
Brett Cannon | ea59dbf | 2012-04-20 21:44:46 -0400 | [diff] [blame] | 407 | """Given the path to a .py file, return the path to its .pyc/.pyo file. |
| 408 | |
| 409 | The .py file does not need to exist; this simply returns the path to the |
| 410 | .pyc/.pyo file calculated as if the .py file were imported. The extension |
Benjamin Peterson | feaa54f | 2012-09-25 11:22:59 -0400 | [diff] [blame] | 411 | will be .pyc unless sys.flags.optimize is non-zero, then it will be .pyo. |
Brett Cannon | ea59dbf | 2012-04-20 21:44:46 -0400 | [diff] [blame] | 412 | |
Benjamin Peterson | 52c62d8 | 2012-09-26 00:25:10 -0400 | [diff] [blame] | 413 | If debug_override is not None, then it must be a boolean and is used in |
| 414 | place of sys.flags.optimize. |
Brett Cannon | ea59dbf | 2012-04-20 21:44:46 -0400 | [diff] [blame] | 415 | |
Brett Cannon | 19a2f59 | 2012-07-09 13:58:07 -0400 | [diff] [blame] | 416 | If sys.implementation.cache_tag is None then NotImplementedError is raised. |
| 417 | |
Brett Cannon | ea59dbf | 2012-04-20 21:44:46 -0400 | [diff] [blame] | 418 | """ |
Benjamin Peterson | feaa54f | 2012-09-25 11:22:59 -0400 | [diff] [blame] | 419 | debug = not sys.flags.optimize if debug_override is None else debug_override |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 420 | if debug: |
| 421 | suffixes = DEBUG_BYTECODE_SUFFIXES |
| 422 | else: |
| 423 | suffixes = OPTIMIZED_BYTECODE_SUFFIXES |
Brett Cannon | ea59dbf | 2012-04-20 21:44:46 -0400 | [diff] [blame] | 424 | head, tail = _path_split(path) |
| 425 | base_filename, sep, _ = tail.partition('.') |
Brett Cannon | 19a2f59 | 2012-07-09 13:58:07 -0400 | [diff] [blame] | 426 | tag = sys.implementation.cache_tag |
| 427 | if tag is None: |
| 428 | raise NotImplementedError('sys.implementation.cache_tag is None') |
| 429 | filename = ''.join([base_filename, sep, tag, suffixes[0]]) |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 430 | return _path_join(head, _PYCACHE, filename) |
Brett Cannon | ea59dbf | 2012-04-20 21:44:46 -0400 | [diff] [blame] | 431 | |
| 432 | |
Brett Cannon | a6473f9 | 2012-07-13 13:57:03 -0400 | [diff] [blame] | 433 | def source_from_cache(path): |
| 434 | """Given the path to a .pyc./.pyo file, return the path to its .py file. |
| 435 | |
| 436 | The .pyc/.pyo file does not need to exist; this simply returns the path to |
| 437 | the .py file calculated to correspond to the .pyc/.pyo file. If path does |
| 438 | not conform to PEP 3147 format, ValueError will be raised. If |
| 439 | sys.implementation.cache_tag is None then NotImplementedError is raised. |
| 440 | |
| 441 | """ |
| 442 | if sys.implementation.cache_tag is None: |
| 443 | raise NotImplementedError('sys.implementation.cache_tag is None') |
| 444 | head, pycache_filename = _path_split(path) |
| 445 | head, pycache = _path_split(head) |
| 446 | if pycache != _PYCACHE: |
| 447 | raise ValueError('{} not bottom-level directory in ' |
| 448 | '{!r}'.format(_PYCACHE, path)) |
| 449 | if pycache_filename.count('.') != 2: |
| 450 | raise ValueError('expected only 2 dots in ' |
| 451 | '{!r}'.format(pycache_filename)) |
| 452 | base_filename = pycache_filename.partition('.')[0] |
| 453 | return _path_join(head, base_filename + SOURCE_SUFFIXES[0]) |
| 454 | |
| 455 | |
| 456 | def _get_sourcefile(bytecode_path): |
| 457 | """Convert a bytecode file path to a source path (if possible). |
| 458 | |
| 459 | This function exists purely for backwards-compatibility for |
| 460 | PyImport_ExecCodeModuleWithFilenames() in the C API. |
| 461 | |
| 462 | """ |
| 463 | if len(bytecode_path) == 0: |
| 464 | return None |
| 465 | rest, _, extension = bytecode_path.rparition('.') |
| 466 | if not rest or extension.lower()[-3:-1] != '.py': |
| 467 | return bytecode_path |
| 468 | |
| 469 | try: |
| 470 | source_path = source_from_cache(bytecode_path) |
| 471 | except (NotImplementedError, ValueError): |
| 472 | source_path = bytcode_path[-1:] |
| 473 | |
| 474 | return source_path if _path_isfile(source_stats) else bytecode_path |
| 475 | |
| 476 | |
Brett Cannon | f8ffec0 | 2013-04-01 13:10:51 -0400 | [diff] [blame] | 477 | def _verbose_message(message, *args, verbosity=1): |
Brett Cannon | fd07415 | 2012-04-14 14:10:13 -0400 | [diff] [blame] | 478 | """Print the message to stderr if -v/PYTHONVERBOSE is turned on.""" |
Brett Cannon | f8ffec0 | 2013-04-01 13:10:51 -0400 | [diff] [blame] | 479 | if sys.flags.verbose >= verbosity: |
Philip Jenvey | f8f3190 | 2012-04-15 12:21:32 -0700 | [diff] [blame] | 480 | if not message.startswith(('#', 'import ')): |
Brett Cannon | fd07415 | 2012-04-14 14:10:13 -0400 | [diff] [blame] | 481 | message = '# ' + message |
| 482 | print(message.format(*args), file=sys.stderr) |
| 483 | |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 484 | |
Brett Cannon | 435aad8 | 2009-03-04 16:07:00 +0000 | [diff] [blame] | 485 | def set_package(fxn): |
Brett Cannon | 06c9d96 | 2009-02-07 01:52:25 +0000 | [diff] [blame] | 486 | """Set __package__ on the returned module.""" |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 487 | def set_package_wrapper(*args, **kwargs): |
Brett Cannon | 06c9d96 | 2009-02-07 01:52:25 +0000 | [diff] [blame] | 488 | module = fxn(*args, **kwargs) |
Florent Xicluna | 79d79a0 | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 489 | if getattr(module, '__package__', None) is None: |
Brett Cannon | 06c9d96 | 2009-02-07 01:52:25 +0000 | [diff] [blame] | 490 | module.__package__ = module.__name__ |
| 491 | if not hasattr(module, '__path__'): |
| 492 | module.__package__ = module.__package__.rpartition('.')[0] |
| 493 | return module |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 494 | _wrap(set_package_wrapper, fxn) |
| 495 | return set_package_wrapper |
Brett Cannon | 06c9d96 | 2009-02-07 01:52:25 +0000 | [diff] [blame] | 496 | |
| 497 | |
Brett Cannon | 2cf03a8 | 2009-03-10 05:17:37 +0000 | [diff] [blame] | 498 | def set_loader(fxn): |
| 499 | """Set __loader__ on the returned module.""" |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 500 | def set_loader_wrapper(self, *args, **kwargs): |
Brett Cannon | 2cf03a8 | 2009-03-10 05:17:37 +0000 | [diff] [blame] | 501 | module = fxn(self, *args, **kwargs) |
Brett Cannon | 4802bec | 2013-03-13 10:41:36 -0700 | [diff] [blame] | 502 | if getattr(module, '__loader__', None) is None: |
Brett Cannon | 2cf03a8 | 2009-03-10 05:17:37 +0000 | [diff] [blame] | 503 | module.__loader__ = self |
| 504 | return module |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 505 | _wrap(set_loader_wrapper, fxn) |
| 506 | return set_loader_wrapper |
Brett Cannon | 2cf03a8 | 2009-03-10 05:17:37 +0000 | [diff] [blame] | 507 | |
| 508 | |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 509 | def module_for_loader(fxn): |
| 510 | """Decorator to handle selecting the proper module for loaders. |
| 511 | |
Brett Cannon | 0e0d8a6 | 2009-03-15 00:00:19 +0000 | [diff] [blame] | 512 | The decorated function is passed the module to use instead of the module |
| 513 | name. The module passed in to the function is either from sys.modules if |
Brett Cannon | efad00d | 2012-04-27 17:27:14 -0400 | [diff] [blame] | 514 | it already exists or is a new module. If the module is new, then __name__ |
| 515 | is set the first argument to the method, __loader__ is set to self, and |
| 516 | __package__ is set accordingly (if self.is_package() is defined) will be set |
| 517 | before it is passed to the decorated function (if self.is_package() does |
| 518 | not work for the module it will be set post-load). |
| 519 | |
| 520 | If an exception is raised and the decorator created the module it is |
| 521 | subsequently removed from sys.modules. |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 522 | |
Brett Cannon | 0e0d8a6 | 2009-03-15 00:00:19 +0000 | [diff] [blame] | 523 | The decorator assumes that the decorated function takes the module name as |
| 524 | the second argument. |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 525 | |
| 526 | """ |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 527 | def module_for_loader_wrapper(self, fullname, *args, **kwargs): |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 528 | module = sys.modules.get(fullname) |
Brett Cannon | 7bd329d | 2012-04-17 21:41:35 -0400 | [diff] [blame] | 529 | is_reload = module is not None |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 530 | if not is_reload: |
| 531 | # This must be done before open() is called as the 'io' module |
| 532 | # implicitly imports 'locale' and would otherwise trigger an |
| 533 | # infinite loop. |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 534 | module = new_module(fullname) |
Antoine Pitrou | 4f0338c | 2012-08-28 00:24:52 +0200 | [diff] [blame] | 535 | # This must be done before putting the module in sys.modules |
| 536 | # (otherwise an optimization shortcut in import.c becomes wrong) |
| 537 | module.__initializing__ = True |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 538 | sys.modules[fullname] = module |
Brett Cannon | efad00d | 2012-04-27 17:27:14 -0400 | [diff] [blame] | 539 | module.__loader__ = self |
| 540 | try: |
| 541 | is_package = self.is_package(fullname) |
| 542 | except (ImportError, AttributeError): |
| 543 | pass |
| 544 | else: |
| 545 | if is_package: |
| 546 | module.__package__ = fullname |
| 547 | else: |
| 548 | module.__package__ = fullname.rpartition('.')[0] |
Antoine Pitrou | 4f0338c | 2012-08-28 00:24:52 +0200 | [diff] [blame] | 549 | else: |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 550 | module.__initializing__ = True |
Antoine Pitrou | 4f0338c | 2012-08-28 00:24:52 +0200 | [diff] [blame] | 551 | try: |
Brett Cannon | efad00d | 2012-04-27 17:27:14 -0400 | [diff] [blame] | 552 | # If __package__ was not set above, __import__() will do it later. |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 553 | return fxn(self, module, *args, **kwargs) |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 554 | except: |
| 555 | if not is_reload: |
| 556 | del sys.modules[fullname] |
| 557 | raise |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 558 | finally: |
| 559 | module.__initializing__ = False |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 560 | _wrap(module_for_loader_wrapper, fxn) |
| 561 | return module_for_loader_wrapper |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 562 | |
| 563 | |
| 564 | def _check_name(method): |
| 565 | """Decorator to verify that the module being requested matches the one the |
| 566 | loader can handle. |
| 567 | |
| 568 | The first argument (self) must define _name which the second argument is |
Ezio Melotti | 42da663 | 2011-03-15 05:18:48 +0200 | [diff] [blame] | 569 | compared against. If the comparison fails then ImportError is raised. |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 570 | |
| 571 | """ |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 572 | def _check_name_wrapper(self, name=None, *args, **kwargs): |
| 573 | if name is None: |
| 574 | name = self.name |
| 575 | elif self.name != name: |
Brett Cannon | bbb6680 | 2012-04-12 21:09:01 -0400 | [diff] [blame] | 576 | raise ImportError("loader cannot handle %s" % name, name=name) |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 577 | return method(self, name, *args, **kwargs) |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 578 | _wrap(_check_name_wrapper, method) |
| 579 | return _check_name_wrapper |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 580 | |
| 581 | |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 582 | def _requires_builtin(fxn): |
| 583 | """Decorator to verify the named module is built-in.""" |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 584 | def _requires_builtin_wrapper(self, fullname): |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 585 | if fullname not in sys.builtin_module_names: |
Florent Xicluna | 79d79a0 | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 586 | raise ImportError("{} is not a built-in module".format(fullname), |
Brett Cannon | bbb6680 | 2012-04-12 21:09:01 -0400 | [diff] [blame] | 587 | name=fullname) |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 588 | return fxn(self, fullname) |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 589 | _wrap(_requires_builtin_wrapper, fxn) |
| 590 | return _requires_builtin_wrapper |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 591 | |
| 592 | |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 593 | def _requires_frozen(fxn): |
| 594 | """Decorator to verify the named module is frozen.""" |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 595 | def _requires_frozen_wrapper(self, fullname): |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 596 | if not _imp.is_frozen(fullname): |
Florent Xicluna | 79d79a0 | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 597 | raise ImportError("{} is not a frozen module".format(fullname), |
Brett Cannon | bbb6680 | 2012-04-12 21:09:01 -0400 | [diff] [blame] | 598 | name=fullname) |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 599 | return fxn(self, fullname) |
Brett Cannon | f522aea | 2012-01-16 11:46:22 -0500 | [diff] [blame] | 600 | _wrap(_requires_frozen_wrapper, fxn) |
| 601 | return _requires_frozen_wrapper |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 602 | |
| 603 | |
Brett Cannon | f410ce8 | 2012-08-10 17:41:23 -0400 | [diff] [blame] | 604 | def _find_module_shim(self, fullname): |
| 605 | """Try to find a loader for the specified module by delegating to |
| 606 | self.find_loader().""" |
| 607 | # Call find_loader(). If it returns a string (indicating this |
| 608 | # is a namespace package portion), generate a warning and |
| 609 | # return None. |
| 610 | loader, portions = self.find_loader(fullname) |
| 611 | if loader is None and len(portions): |
| 612 | msg = "Not importing directory {}: missing __init__" |
| 613 | _warnings.warn(msg.format(portions[0]), ImportWarning) |
| 614 | return loader |
| 615 | |
| 616 | |
Brett Cannon | 569ff4f | 2013-01-11 18:09:25 -0500 | [diff] [blame] | 617 | def _validate_bytecode_header(data, source_stats=None, name=None, path=None): |
| 618 | """Validate the header of the passed-in bytecode against source_stats (if |
| 619 | given) and returning the bytecode that can be compiled by compile(). |
| 620 | |
| 621 | All other arguments are used to enhance error reporting. |
| 622 | |
| 623 | ImportError is raised when the magic number is incorrect or the bytecode is |
| 624 | found to be stale. EOFError is raised when the data is found to be |
| 625 | truncated. |
| 626 | |
| 627 | """ |
| 628 | exc_details = {} |
| 629 | if name is not None: |
| 630 | exc_details['name'] = name |
| 631 | else: |
| 632 | # To prevent having to make all messages have a conditional name. |
Brett Cannon | 686e880 | 2013-01-25 13:49:19 -0500 | [diff] [blame] | 633 | name = '<bytecode>' |
Brett Cannon | 569ff4f | 2013-01-11 18:09:25 -0500 | [diff] [blame] | 634 | if path is not None: |
| 635 | exc_details['path'] = path |
| 636 | magic = data[:4] |
| 637 | raw_timestamp = data[4:8] |
| 638 | raw_size = data[8:12] |
| 639 | if magic != _MAGIC_BYTES: |
Brett Cannon | daf4daa | 2013-04-01 13:25:40 -0400 | [diff] [blame] | 640 | message = 'bad magic number in {!r}: {!r}'.format(name, magic) |
| 641 | _verbose_message(message) |
| 642 | raise ImportError(message, **exc_details) |
Brett Cannon | 569ff4f | 2013-01-11 18:09:25 -0500 | [diff] [blame] | 643 | elif len(raw_timestamp) != 4: |
Brett Cannon | 686e880 | 2013-01-25 13:49:19 -0500 | [diff] [blame] | 644 | message = 'incomplete timestamp in {!r}'.format(name) |
Brett Cannon | 569ff4f | 2013-01-11 18:09:25 -0500 | [diff] [blame] | 645 | _verbose_message(message) |
| 646 | raise EOFError(message) |
| 647 | elif len(raw_size) != 4: |
Brett Cannon | 686e880 | 2013-01-25 13:49:19 -0500 | [diff] [blame] | 648 | message = 'incomplete size in {!r}'.format(name) |
Brett Cannon | 569ff4f | 2013-01-11 18:09:25 -0500 | [diff] [blame] | 649 | _verbose_message(message) |
| 650 | raise EOFError(message) |
| 651 | if source_stats is not None: |
| 652 | try: |
| 653 | source_mtime = int(source_stats['mtime']) |
| 654 | except KeyError: |
| 655 | pass |
| 656 | else: |
| 657 | if _r_long(raw_timestamp) != source_mtime: |
| 658 | message = 'bytecode is stale for {!r}'.format(name) |
| 659 | _verbose_message(message) |
| 660 | raise ImportError(message, **exc_details) |
| 661 | try: |
| 662 | source_size = source_stats['size'] & 0xFFFFFFFF |
| 663 | except KeyError: |
| 664 | pass |
| 665 | else: |
| 666 | if _r_long(raw_size) != source_size: |
| 667 | raise ImportError("bytecode is stale for {!r}".format(name), |
| 668 | **exc_details) |
| 669 | return data[12:] |
| 670 | |
| 671 | |
| 672 | def _compile_bytecode(data, name=None, bytecode_path=None, source_path=None): |
| 673 | """Compile bytecode as returned by _validate_bytecode_header().""" |
| 674 | code = marshal.loads(data) |
| 675 | if isinstance(code, _code_type): |
| 676 | _verbose_message('code object from {!r}', bytecode_path) |
| 677 | if source_path is not None: |
| 678 | _imp._fix_co_filename(code, source_path) |
| 679 | return code |
| 680 | else: |
| 681 | raise ImportError("Non-code object in {!r}".format(bytecode_path), |
| 682 | name=name, path=bytecode_path) |
Brett Cannon | f410ce8 | 2012-08-10 17:41:23 -0400 | [diff] [blame] | 683 | |
Brett Cannon | 14581d5 | 2013-01-26 08:48:36 -0500 | [diff] [blame] | 684 | def _code_to_bytecode(code, mtime=0, source_size=0): |
| 685 | """Compile a code object into bytecode for writing out to a byte-compiled |
| 686 | file.""" |
| 687 | data = bytearray(_MAGIC_BYTES) |
| 688 | data.extend(_w_long(mtime)) |
| 689 | data.extend(_w_long(source_size)) |
| 690 | data.extend(marshal.dumps(code)) |
| 691 | return data |
| 692 | |
Brett Cannon | f410ce8 | 2012-08-10 17:41:23 -0400 | [diff] [blame] | 693 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 694 | # Loaders ##################################################################### |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 695 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 696 | class BuiltinImporter: |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 697 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 698 | """Meta path import for built-in modules. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 699 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 700 | All methods are either class or static methods to avoid the need to |
| 701 | instantiate the class. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 702 | |
| 703 | """ |
| 704 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 705 | @classmethod |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 706 | def module_repr(cls, module): |
| 707 | return "<module '{}' (built-in)>".format(module.__name__) |
| 708 | |
| 709 | @classmethod |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 710 | def find_module(cls, fullname, path=None): |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 711 | """Find the built-in module. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 712 | |
| 713 | If 'path' is ever specified then the search is considered a failure. |
| 714 | |
| 715 | """ |
| 716 | if path is not None: |
| 717 | return None |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 718 | return cls if _imp.is_builtin(fullname) else None |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 719 | |
Brett Cannon | 78246b6 | 2009-01-25 04:56:30 +0000 | [diff] [blame] | 720 | @classmethod |
Brett Cannon | 435aad8 | 2009-03-04 16:07:00 +0000 | [diff] [blame] | 721 | @set_package |
Brett Cannon | 2cf03a8 | 2009-03-10 05:17:37 +0000 | [diff] [blame] | 722 | @set_loader |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 723 | @_requires_builtin |
Brett Cannon | 78246b6 | 2009-01-25 04:56:30 +0000 | [diff] [blame] | 724 | def load_module(cls, fullname): |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 725 | """Load a built-in module.""" |
Brett Cannon | d2e7b33 | 2009-02-17 02:45:03 +0000 | [diff] [blame] | 726 | is_reload = fullname in sys.modules |
| 727 | try: |
Nick Coghlan | 42c0766 | 2012-07-31 21:14:18 +1000 | [diff] [blame] | 728 | return _call_with_frames_removed(_imp.init_builtin, fullname) |
Brett Cannon | d2e7b33 | 2009-02-17 02:45:03 +0000 | [diff] [blame] | 729 | except: |
| 730 | if not is_reload and fullname in sys.modules: |
| 731 | del sys.modules[fullname] |
| 732 | raise |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 733 | |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 734 | @classmethod |
| 735 | @_requires_builtin |
| 736 | def get_code(cls, fullname): |
| 737 | """Return None as built-in modules do not have code objects.""" |
| 738 | return None |
| 739 | |
| 740 | @classmethod |
| 741 | @_requires_builtin |
| 742 | def get_source(cls, fullname): |
| 743 | """Return None as built-in modules do not have source code.""" |
| 744 | return None |
| 745 | |
| 746 | @classmethod |
| 747 | @_requires_builtin |
| 748 | def is_package(cls, fullname): |
Florent Xicluna | 79d79a0 | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 749 | """Return False as built-in modules are never packages.""" |
Brett Cannon | a113ac5 | 2009-03-15 01:41:33 +0000 | [diff] [blame] | 750 | return False |
| 751 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 752 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 753 | class FrozenImporter: |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 754 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 755 | """Meta path import for frozen modules. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 756 | |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 757 | All methods are either class or static methods to avoid the need to |
| 758 | instantiate the class. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 759 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 760 | """ |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 761 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 762 | @classmethod |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 763 | def module_repr(cls, m): |
| 764 | return "<module '{}' (frozen)>".format(m.__name__) |
| 765 | |
| 766 | @classmethod |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 767 | def find_module(cls, fullname, path=None): |
| 768 | """Find a frozen module.""" |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 769 | return cls if _imp.is_frozen(fullname) else None |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 770 | |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 771 | @classmethod |
Brett Cannon | 435aad8 | 2009-03-04 16:07:00 +0000 | [diff] [blame] | 772 | @set_package |
Brett Cannon | 2cf03a8 | 2009-03-10 05:17:37 +0000 | [diff] [blame] | 773 | @set_loader |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 774 | @_requires_frozen |
Brett Cannon | 5abdc93 | 2009-01-22 22:43:07 +0000 | [diff] [blame] | 775 | def load_module(cls, fullname): |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 776 | """Load a frozen module.""" |
Brett Cannon | d2e7b33 | 2009-02-17 02:45:03 +0000 | [diff] [blame] | 777 | is_reload = fullname in sys.modules |
| 778 | try: |
Nick Coghlan | 42c0766 | 2012-07-31 21:14:18 +1000 | [diff] [blame] | 779 | m = _call_with_frames_removed(_imp.init_frozen, fullname) |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 780 | # Let our own module_repr() method produce a suitable repr. |
| 781 | del m.__file__ |
| 782 | return m |
Brett Cannon | d2e7b33 | 2009-02-17 02:45:03 +0000 | [diff] [blame] | 783 | except: |
| 784 | if not is_reload and fullname in sys.modules: |
| 785 | del sys.modules[fullname] |
| 786 | raise |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 787 | |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 788 | @classmethod |
| 789 | @_requires_frozen |
| 790 | def get_code(cls, fullname): |
| 791 | """Return the code object for the frozen module.""" |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 792 | return _imp.get_frozen_object(fullname) |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 793 | |
| 794 | @classmethod |
| 795 | @_requires_frozen |
| 796 | def get_source(cls, fullname): |
| 797 | """Return None as frozen modules do not have source code.""" |
| 798 | return None |
| 799 | |
| 800 | @classmethod |
| 801 | @_requires_frozen |
| 802 | def is_package(cls, fullname): |
Philip Jenvey | 688a551 | 2012-08-10 16:21:35 -0700 | [diff] [blame] | 803 | """Return True if the frozen module is a package.""" |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 804 | return _imp.is_frozen_package(fullname) |
Brett Cannon | 8d11013 | 2009-03-15 02:20:16 +0000 | [diff] [blame] | 805 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 806 | |
Nick Coghlan | ff79486 | 2012-08-02 21:45:24 +1000 | [diff] [blame] | 807 | class WindowsRegistryFinder: |
Martin v. Löwis | e3010a8 | 2012-07-28 21:33:05 +0200 | [diff] [blame] | 808 | |
Nick Coghlan | ff79486 | 2012-08-02 21:45:24 +1000 | [diff] [blame] | 809 | """Meta path finder for modules declared in the Windows registry. |
Martin v. Löwis | e3010a8 | 2012-07-28 21:33:05 +0200 | [diff] [blame] | 810 | """ |
| 811 | |
| 812 | REGISTRY_KEY = ( |
| 813 | "Software\\Python\\PythonCore\\{sys_version}" |
| 814 | "\\Modules\\{fullname}") |
| 815 | REGISTRY_KEY_DEBUG = ( |
| 816 | "Software\\Python\\PythonCore\\{sys_version}" |
| 817 | "\\Modules\\{fullname}\\Debug") |
| 818 | DEBUG_BUILD = False # Changed in _setup() |
| 819 | |
| 820 | @classmethod |
| 821 | def _open_registry(cls, key): |
| 822 | try: |
| 823 | return _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, key) |
Andrew Svetlov | 2606a6f | 2012-12-19 14:33:35 +0200 | [diff] [blame] | 824 | except OSError: |
Martin v. Löwis | e3010a8 | 2012-07-28 21:33:05 +0200 | [diff] [blame] | 825 | return _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key) |
| 826 | |
| 827 | @classmethod |
| 828 | def _search_registry(cls, fullname): |
| 829 | if cls.DEBUG_BUILD: |
| 830 | registry_key = cls.REGISTRY_KEY_DEBUG |
| 831 | else: |
| 832 | registry_key = cls.REGISTRY_KEY |
| 833 | key = registry_key.format(fullname=fullname, |
| 834 | sys_version=sys.version[:3]) |
| 835 | try: |
| 836 | with cls._open_registry(key) as hkey: |
| 837 | filepath = _winreg.QueryValue(hkey, "") |
Andrew Svetlov | 2606a6f | 2012-12-19 14:33:35 +0200 | [diff] [blame] | 838 | except OSError: |
Martin v. Löwis | e3010a8 | 2012-07-28 21:33:05 +0200 | [diff] [blame] | 839 | return None |
| 840 | return filepath |
| 841 | |
| 842 | @classmethod |
| 843 | def find_module(cls, fullname, path=None): |
| 844 | """Find module named in the registry.""" |
| 845 | filepath = cls._search_registry(fullname) |
| 846 | if filepath is None: |
| 847 | return None |
| 848 | try: |
| 849 | _os.stat(filepath) |
| 850 | except OSError: |
| 851 | return None |
| 852 | for loader, suffixes, _ in _get_supported_file_loaders(): |
| 853 | if filepath.endswith(tuple(suffixes)): |
| 854 | return loader(fullname, filepath) |
| 855 | |
| 856 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 857 | class _LoaderBasics: |
| 858 | |
| 859 | """Base class of common code needed by both SourceLoader and |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 860 | SourcelessFileLoader.""" |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 861 | |
| 862 | def is_package(self, fullname): |
| 863 | """Concrete implementation of InspectLoader.is_package by checking if |
| 864 | the path returned by get_filename has a filename of '__init__.py'.""" |
Brett Cannon | ed672d6 | 2012-04-20 21:19:53 -0400 | [diff] [blame] | 865 | filename = _path_split(self.get_filename(fullname))[1] |
Brett Cannon | ea0b823 | 2012-06-15 20:00:53 -0400 | [diff] [blame] | 866 | filename_base = filename.rsplit('.', 1)[0] |
| 867 | tail_name = fullname.rpartition('.')[2] |
| 868 | return filename_base == '__init__' and tail_name != '__init__' |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 869 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 870 | @module_for_loader |
| 871 | def _load_module(self, module, *, sourceless=False): |
| 872 | """Helper for load_module able to handle either source or sourceless |
| 873 | loading.""" |
| 874 | name = module.__name__ |
| 875 | code_object = self.get_code(name) |
| 876 | module.__file__ = self.get_filename(name) |
| 877 | if not sourceless: |
Brett Cannon | 19a2f59 | 2012-07-09 13:58:07 -0400 | [diff] [blame] | 878 | try: |
| 879 | module.__cached__ = cache_from_source(module.__file__) |
| 880 | except NotImplementedError: |
| 881 | module.__cached__ = module.__file__ |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 882 | else: |
| 883 | module.__cached__ = module.__file__ |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 884 | if self.is_package(name): |
Brett Cannon | ed672d6 | 2012-04-20 21:19:53 -0400 | [diff] [blame] | 885 | module.__path__ = [_path_split(module.__file__)[0]] |
Brett Cannon | 4802bec | 2013-03-13 10:41:36 -0700 | [diff] [blame] | 886 | # __package__ and __loader set by @module_for_loader. |
Nick Coghlan | 42c0766 | 2012-07-31 21:14:18 +1000 | [diff] [blame] | 887 | _call_with_frames_removed(exec, code_object, module.__dict__) |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 888 | return module |
| 889 | |
| 890 | |
| 891 | class SourceLoader(_LoaderBasics): |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 892 | |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 893 | def path_mtime(self, path): |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 894 | """Optional method that returns the modification time (an int) for the |
| 895 | specified path, where path is a str. |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 896 | """ |
| 897 | raise NotImplementedError |
| 898 | |
Antoine Pitrou | 5136ac0 | 2012-01-13 18:52:16 +0100 | [diff] [blame] | 899 | def path_stats(self, path): |
| 900 | """Optional method returning a metadata dict for the specified path |
| 901 | to by the path (str). |
| 902 | Possible keys: |
| 903 | - 'mtime' (mandatory) is the numeric timestamp of last source |
| 904 | code modification; |
| 905 | - 'size' (optional) is the size in bytes of the source code. |
| 906 | |
| 907 | Implementing this method allows the loader to read bytecode files. |
| 908 | """ |
| 909 | return {'mtime': self.path_mtime(path)} |
| 910 | |
Nick Coghlan | a508770 | 2012-08-24 18:32:40 +1000 | [diff] [blame] | 911 | def _cache_bytecode(self, source_path, cache_path, data): |
| 912 | """Optional method which writes data (bytes) to a file path (a str). |
| 913 | |
| 914 | Implementing this method allows for the writing of bytecode files. |
| 915 | |
| 916 | The source path is needed in order to correctly transfer permissions |
| 917 | """ |
| 918 | # For backwards compatibility, we delegate to set_data() |
| 919 | return self.set_data(cache_path, data) |
| 920 | |
Raymond Hettinger | cd92f37 | 2011-01-13 02:31:25 +0000 | [diff] [blame] | 921 | def set_data(self, path, data): |
Raymond Hettinger | d958ea7 | 2011-01-13 19:08:04 +0000 | [diff] [blame] | 922 | """Optional method which writes data (bytes) to a file path (a str). |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 923 | |
| 924 | Implementing this method allows for the writing of bytecode files. |
| 925 | |
| 926 | """ |
| 927 | raise NotImplementedError |
| 928 | |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 929 | |
| 930 | def get_source(self, fullname): |
| 931 | """Concrete implementation of InspectLoader.get_source.""" |
| 932 | import tokenize |
| 933 | path = self.get_filename(fullname) |
| 934 | try: |
| 935 | source_bytes = self.get_data(path) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 936 | except OSError as exc: |
Brett Cannon | bbb6680 | 2012-04-12 21:09:01 -0400 | [diff] [blame] | 937 | raise ImportError("source not available through get_data()", |
Nick Coghlan | 2824cb5 | 2012-07-15 22:12:14 +1000 | [diff] [blame] | 938 | name=fullname) from exc |
| 939 | readsource = _io.BytesIO(source_bytes).readline |
| 940 | try: |
| 941 | encoding = tokenize.detect_encoding(readsource) |
| 942 | except SyntaxError as exc: |
| 943 | raise ImportError("Failed to detect encoding", |
| 944 | name=fullname) from exc |
Brett Cannon | 418182e | 2010-07-03 22:32:41 +0000 | [diff] [blame] | 945 | newline_decoder = _io.IncrementalNewlineDecoder(None, True) |
Nick Coghlan | 2824cb5 | 2012-07-15 22:12:14 +1000 | [diff] [blame] | 946 | try: |
| 947 | return newline_decoder.decode(source_bytes.decode(encoding[0])) |
| 948 | except UnicodeDecodeError as exc: |
| 949 | raise ImportError("Failed to decode source file", |
| 950 | name=fullname) from exc |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 951 | |
Brett Cannon | 14581d5 | 2013-01-26 08:48:36 -0500 | [diff] [blame] | 952 | def source_to_code(self, data, path, *, _optimize=-1): |
Brett Cannon | 5650e4f | 2012-11-18 10:03:31 -0500 | [diff] [blame] | 953 | """Return the code object compiled from source. |
| 954 | |
| 955 | The 'data' argument can be any object type that compile() supports. |
| 956 | """ |
| 957 | return _call_with_frames_removed(compile, data, path, 'exec', |
Brett Cannon | 14581d5 | 2013-01-26 08:48:36 -0500 | [diff] [blame] | 958 | dont_inherit=True, optimize=_optimize) |
Brett Cannon | 5650e4f | 2012-11-18 10:03:31 -0500 | [diff] [blame] | 959 | |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 960 | def get_code(self, fullname): |
| 961 | """Concrete implementation of InspectLoader.get_code. |
| 962 | |
Antoine Pitrou | 5136ac0 | 2012-01-13 18:52:16 +0100 | [diff] [blame] | 963 | Reading of bytecode requires path_stats to be implemented. To write |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 964 | bytecode, set_data must also be implemented. |
| 965 | |
| 966 | """ |
| 967 | source_path = self.get_filename(fullname) |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 968 | source_mtime = None |
Brett Cannon | 19a2f59 | 2012-07-09 13:58:07 -0400 | [diff] [blame] | 969 | try: |
| 970 | bytecode_path = cache_from_source(source_path) |
| 971 | except NotImplementedError: |
| 972 | bytecode_path = None |
| 973 | else: |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 974 | try: |
Antoine Pitrou | 5136ac0 | 2012-01-13 18:52:16 +0100 | [diff] [blame] | 975 | st = self.path_stats(source_path) |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 976 | except NotImplementedError: |
| 977 | pass |
| 978 | else: |
Antoine Pitrou | 5136ac0 | 2012-01-13 18:52:16 +0100 | [diff] [blame] | 979 | source_mtime = int(st['mtime']) |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 980 | try: |
| 981 | data = self.get_data(bytecode_path) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 982 | except OSError: |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 983 | pass |
| 984 | else: |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 985 | try: |
Brett Cannon | 569ff4f | 2013-01-11 18:09:25 -0500 | [diff] [blame] | 986 | bytes_data = _validate_bytecode_header(data, |
| 987 | source_stats=st, name=fullname, |
| 988 | path=bytecode_path) |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 989 | except (ImportError, EOFError): |
| 990 | pass |
| 991 | else: |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 992 | _verbose_message('{} matches {}', bytecode_path, |
Brett Cannon | fd07415 | 2012-04-14 14:10:13 -0400 | [diff] [blame] | 993 | source_path) |
Brett Cannon | 569ff4f | 2013-01-11 18:09:25 -0500 | [diff] [blame] | 994 | return _compile_bytecode(bytes_data, name=fullname, |
| 995 | bytecode_path=bytecode_path, |
| 996 | source_path=source_path) |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 997 | source_bytes = self.get_data(source_path) |
Eric Snow | a6cfb28 | 2012-12-04 23:43:43 -0800 | [diff] [blame] | 998 | code_object = self.source_to_code(source_bytes, source_path) |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 999 | _verbose_message('code object from {}', source_path) |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 1000 | if (not sys.dont_write_bytecode and bytecode_path is not None and |
Brett Cannon | 14581d5 | 2013-01-26 08:48:36 -0500 | [diff] [blame] | 1001 | source_mtime is not None): |
| 1002 | data = _code_to_bytecode(code_object, source_mtime, |
| 1003 | len(source_bytes)) |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 1004 | try: |
Nick Coghlan | a508770 | 2012-08-24 18:32:40 +1000 | [diff] [blame] | 1005 | self._cache_bytecode(source_path, bytecode_path, data) |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 1006 | _verbose_message('wrote {!r}', bytecode_path) |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 1007 | except NotImplementedError: |
| 1008 | pass |
| 1009 | return code_object |
| 1010 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1011 | def load_module(self, fullname): |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 1012 | """Concrete implementation of Loader.load_module. |
| 1013 | |
| 1014 | Requires ExecutionLoader.get_filename and ResourceLoader.get_data to be |
| 1015 | implemented to load source code. Use of bytecode is dictated by whether |
| 1016 | get_code uses/writes bytecode. |
| 1017 | |
| 1018 | """ |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1019 | return self._load_module(fullname) |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 1020 | |
| 1021 | |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 1022 | class FileLoader: |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 1023 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1024 | """Base file loader class which implements the loader protocol methods that |
| 1025 | require file system usage.""" |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 1026 | |
| 1027 | def __init__(self, fullname, path): |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1028 | """Cache the module name and the path to the file found by the |
| 1029 | finder.""" |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 1030 | self.name = fullname |
| 1031 | self.path = path |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 1032 | |
| 1033 | @_check_name |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 1034 | def load_module(self, fullname): |
| 1035 | """Load a module from a file.""" |
Nick Coghlan | 5c6eba3 | 2012-05-27 17:49:58 +1000 | [diff] [blame] | 1036 | # Issue #14857: Avoid the zero-argument form so the implementation |
| 1037 | # of that form can be updated without breaking the frozen module |
| 1038 | return super(FileLoader, self).load_module(fullname) |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 1039 | |
| 1040 | @_check_name |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 1041 | def get_filename(self, fullname): |
| 1042 | """Return the path to the source file as found by the finder.""" |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 1043 | return self.path |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 1044 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1045 | def get_data(self, path): |
| 1046 | """Return the data from path as raw bytes.""" |
Florent Xicluna | 764d612 | 2010-09-03 19:55:26 +0000 | [diff] [blame] | 1047 | with _io.FileIO(path, 'r') as file: |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1048 | return file.read() |
| 1049 | |
| 1050 | |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 1051 | class SourceFileLoader(FileLoader, SourceLoader): |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1052 | |
| 1053 | """Concrete implementation of SourceLoader using the file system.""" |
| 1054 | |
Antoine Pitrou | 5136ac0 | 2012-01-13 18:52:16 +0100 | [diff] [blame] | 1055 | def path_stats(self, path): |
Philip Jenvey | 688a551 | 2012-08-10 16:21:35 -0700 | [diff] [blame] | 1056 | """Return the metadata for the path.""" |
Antoine Pitrou | 5136ac0 | 2012-01-13 18:52:16 +0100 | [diff] [blame] | 1057 | st = _os.stat(path) |
| 1058 | return {'mtime': st.st_mtime, 'size': st.st_size} |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 1059 | |
Nick Coghlan | a508770 | 2012-08-24 18:32:40 +1000 | [diff] [blame] | 1060 | def _cache_bytecode(self, source_path, bytecode_path, data): |
| 1061 | # Adapt between the two APIs |
Brett Cannon | ba0a3ed | 2012-08-24 13:48:39 -0400 | [diff] [blame] | 1062 | try: |
| 1063 | mode = _os.stat(source_path).st_mode |
| 1064 | except OSError: |
| 1065 | mode = 0o666 |
Nick Coghlan | eb8d627 | 2012-10-19 23:32:00 +1000 | [diff] [blame] | 1066 | # We always ensure write access so we can update cached files |
| 1067 | # later even when the source files are read-only on Windows (#6074) |
| 1068 | mode |= 0o200 |
Brett Cannon | ba0a3ed | 2012-08-24 13:48:39 -0400 | [diff] [blame] | 1069 | return self.set_data(bytecode_path, data, _mode=mode) |
Nick Coghlan | a508770 | 2012-08-24 18:32:40 +1000 | [diff] [blame] | 1070 | |
Brett Cannon | ba0a3ed | 2012-08-24 13:48:39 -0400 | [diff] [blame] | 1071 | def set_data(self, path, data, *, _mode=0o666): |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 1072 | """Write bytes data to a file.""" |
Brett Cannon | ed672d6 | 2012-04-20 21:19:53 -0400 | [diff] [blame] | 1073 | parent, filename = _path_split(path) |
Brett Cannon | ee6d647 | 2010-08-22 22:19:11 +0000 | [diff] [blame] | 1074 | path_parts = [] |
| 1075 | # Figure out what directories are missing. |
| 1076 | while parent and not _path_isdir(parent): |
Brett Cannon | ed672d6 | 2012-04-20 21:19:53 -0400 | [diff] [blame] | 1077 | parent, part = _path_split(parent) |
Brett Cannon | ee6d647 | 2010-08-22 22:19:11 +0000 | [diff] [blame] | 1078 | path_parts.append(part) |
| 1079 | # Create needed directories. |
| 1080 | for part in reversed(path_parts): |
| 1081 | parent = _path_join(parent, part) |
| 1082 | try: |
| 1083 | _os.mkdir(parent) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 1084 | except FileExistsError: |
Brett Cannon | ee6d647 | 2010-08-22 22:19:11 +0000 | [diff] [blame] | 1085 | # Probably another Python process already created the dir. |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 1086 | continue |
Trent Nelson | d783c8e | 2012-10-16 07:47:34 -0400 | [diff] [blame] | 1087 | except OSError as exc: |
| 1088 | # Could be a permission error, read-only filesystem: just forget |
| 1089 | # about writing the data. |
| 1090 | _verbose_message('could not create {!r}: {!r}', parent, exc) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 1091 | return |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 1092 | try: |
Brett Cannon | ba0a3ed | 2012-08-24 13:48:39 -0400 | [diff] [blame] | 1093 | _write_atomic(path, data, _mode) |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 1094 | _verbose_message('created {!r}', path) |
Trent Nelson | d783c8e | 2012-10-16 07:47:34 -0400 | [diff] [blame] | 1095 | except OSError as exc: |
| 1096 | # Same as above: just don't write the bytecode. |
| 1097 | _verbose_message('could not create {!r}: {!r}', path, exc) |
Brett Cannon | 0cf9e6a | 2010-06-28 04:57:24 +0000 | [diff] [blame] | 1098 | |
| 1099 | |
Marc-Andre Lemburg | 4fe29c9 | 2012-04-25 02:31:37 +0200 | [diff] [blame] | 1100 | class SourcelessFileLoader(FileLoader, _LoaderBasics): |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 1101 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1102 | """Loader which handles sourceless file imports.""" |
Brett Cannon | 91cf882 | 2009-02-21 05:41:15 +0000 | [diff] [blame] | 1103 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1104 | def load_module(self, fullname): |
| 1105 | return self._load_module(fullname, sourceless=True) |
Brett Cannon | 6919427 | 2009-07-20 04:23:48 +0000 | [diff] [blame] | 1106 | |
Brett Cannon | 91cf882 | 2009-02-21 05:41:15 +0000 | [diff] [blame] | 1107 | def get_code(self, fullname): |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1108 | path = self.get_filename(fullname) |
| 1109 | data = self.get_data(path) |
Brett Cannon | 569ff4f | 2013-01-11 18:09:25 -0500 | [diff] [blame] | 1110 | bytes_data = _validate_bytecode_header(data, name=fullname, path=path) |
| 1111 | return _compile_bytecode(bytes_data, name=fullname, bytecode_path=path) |
Brett Cannon | 91cf882 | 2009-02-21 05:41:15 +0000 | [diff] [blame] | 1112 | |
Brett Cannon | d43b30b | 2009-03-10 03:29:23 +0000 | [diff] [blame] | 1113 | def get_source(self, fullname): |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1114 | """Return None as there is no source code.""" |
| 1115 | return None |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 1116 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 1117 | |
Brett Cannon | ac9f2f3 | 2012-08-10 13:47:54 -0400 | [diff] [blame] | 1118 | # Filled in by _setup(). |
| 1119 | EXTENSION_SUFFIXES = [] |
| 1120 | |
| 1121 | |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 1122 | class ExtensionFileLoader: |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 1123 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1124 | """Loader for extension modules. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 1125 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1126 | The constructor is designed to work with FileFinder. |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 1127 | |
| 1128 | """ |
| 1129 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1130 | def __init__(self, name, path): |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 1131 | self.name = name |
| 1132 | self.path = path |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 1133 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1134 | @_check_name |
| 1135 | @set_package |
| 1136 | @set_loader |
| 1137 | def load_module(self, fullname): |
| 1138 | """Load an extension module.""" |
| 1139 | is_reload = fullname in sys.modules |
| 1140 | try: |
Nick Coghlan | 42c0766 | 2012-07-31 21:14:18 +1000 | [diff] [blame] | 1141 | module = _call_with_frames_removed(_imp.load_dynamic, |
| 1142 | fullname, self.path) |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 1143 | _verbose_message('extension module loaded from {!r}', self.path) |
Brett Cannon | b428f47 | 2012-08-11 19:43:29 -0400 | [diff] [blame] | 1144 | if self.is_package(fullname) and not hasattr(module, '__path__'): |
Brett Cannon | ac9f2f3 | 2012-08-10 13:47:54 -0400 | [diff] [blame] | 1145 | module.__path__ = [_path_split(self.path)[0]] |
Brett Cannon | fd07415 | 2012-04-14 14:10:13 -0400 | [diff] [blame] | 1146 | return module |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1147 | except: |
| 1148 | if not is_reload and fullname in sys.modules: |
| 1149 | del sys.modules[fullname] |
| 1150 | raise |
| 1151 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1152 | def is_package(self, fullname): |
Philip Jenvey | 688a551 | 2012-08-10 16:21:35 -0700 | [diff] [blame] | 1153 | """Return True if the extension module is a package.""" |
Brett Cannon | ac9f2f3 | 2012-08-10 13:47:54 -0400 | [diff] [blame] | 1154 | file_name = _path_split(self.path)[1] |
Philip Jenvey | 731d48a | 2012-08-10 11:53:54 -0700 | [diff] [blame] | 1155 | return any(file_name == '__init__' + suffix |
| 1156 | for suffix in EXTENSION_SUFFIXES) |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1157 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1158 | def get_code(self, fullname): |
| 1159 | """Return None as an extension module cannot create a code object.""" |
| 1160 | return None |
| 1161 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1162 | def get_source(self, fullname): |
| 1163 | """Return None as extension modules have no source code.""" |
| 1164 | return None |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 1165 | |
| 1166 | |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 1167 | class _NamespacePath: |
| 1168 | """Represents a namespace package's path. It uses the module name |
| 1169 | to find its parent module, and from there it looks up the parent's |
| 1170 | __path__. When this changes, the module's own path is recomputed, |
Benjamin Peterson | debf64c | 2012-11-12 16:48:17 -0500 | [diff] [blame] | 1171 | using path_finder. For top-level modules, the parent module's path |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 1172 | is sys.path.""" |
| 1173 | |
| 1174 | def __init__(self, name, path, path_finder): |
| 1175 | self._name = name |
| 1176 | self._path = path |
| 1177 | self._last_parent_path = tuple(self._get_parent_path()) |
| 1178 | self._path_finder = path_finder |
| 1179 | |
| 1180 | def _find_parent_path_names(self): |
| 1181 | """Returns a tuple of (parent-module-name, parent-path-attr-name)""" |
| 1182 | parent, dot, me = self._name.rpartition('.') |
| 1183 | if dot == '': |
| 1184 | # This is a top-level module. sys.path contains the parent path. |
| 1185 | return 'sys', 'path' |
| 1186 | # Not a top-level module. parent-module.__path__ contains the |
| 1187 | # parent path. |
| 1188 | return parent, '__path__' |
| 1189 | |
| 1190 | def _get_parent_path(self): |
| 1191 | parent_module_name, path_attr_name = self._find_parent_path_names() |
| 1192 | return getattr(sys.modules[parent_module_name], path_attr_name) |
| 1193 | |
| 1194 | def _recalculate(self): |
| 1195 | # If the parent's path has changed, recalculate _path |
| 1196 | parent_path = tuple(self._get_parent_path()) # Make a copy |
| 1197 | if parent_path != self._last_parent_path: |
| 1198 | loader, new_path = self._path_finder(self._name, parent_path) |
| 1199 | # Note that no changes are made if a loader is returned, but we |
| 1200 | # do remember the new parent path |
| 1201 | if loader is None: |
| 1202 | self._path = new_path |
| 1203 | self._last_parent_path = parent_path # Save the copy |
| 1204 | return self._path |
| 1205 | |
| 1206 | def __iter__(self): |
| 1207 | return iter(self._recalculate()) |
| 1208 | |
| 1209 | def __len__(self): |
| 1210 | return len(self._recalculate()) |
| 1211 | |
| 1212 | def __repr__(self): |
Florent Xicluna | 79d79a0 | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 1213 | return "_NamespacePath({!r})".format(self._path) |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 1214 | |
| 1215 | def __contains__(self, item): |
| 1216 | return item in self._recalculate() |
| 1217 | |
| 1218 | def append(self, item): |
| 1219 | self._path.append(item) |
| 1220 | |
| 1221 | |
| 1222 | class NamespaceLoader: |
| 1223 | def __init__(self, name, path, path_finder): |
| 1224 | self._path = _NamespacePath(name, path, path_finder) |
| 1225 | |
| 1226 | @classmethod |
| 1227 | def module_repr(cls, module): |
| 1228 | return "<module '{}' (namespace)>".format(module.__name__) |
| 1229 | |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 1230 | @module_for_loader |
| 1231 | def load_module(self, module): |
| 1232 | """Load a namespace module.""" |
| 1233 | _verbose_message('namespace module loaded with path {!r}', self._path) |
| 1234 | module.__path__ = self._path |
| 1235 | return module |
| 1236 | |
| 1237 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1238 | # Finders ##################################################################### |
Brett Cannon | 4afab6b | 2009-02-21 03:31:35 +0000 | [diff] [blame] | 1239 | |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 1240 | class PathFinder: |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1241 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 1242 | """Meta path finder for sys.path and package __path__ attributes.""" |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1243 | |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 1244 | @classmethod |
Brett Cannon | f4dc920 | 2012-08-10 12:21:12 -0400 | [diff] [blame] | 1245 | def invalidate_caches(cls): |
| 1246 | """Call the invalidate_caches() method on all path entry finders |
| 1247 | stored in sys.path_importer_caches (where implemented).""" |
| 1248 | for finder in sys.path_importer_cache.values(): |
| 1249 | if hasattr(finder, 'invalidate_caches'): |
| 1250 | finder.invalidate_caches() |
| 1251 | |
| 1252 | @classmethod |
Brett Cannon | e0d88a1 | 2012-04-25 20:54:04 -0400 | [diff] [blame] | 1253 | def _path_hooks(cls, path): |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 1254 | """Search sequence of hooks for a finder for 'path'. |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1255 | |
Brett Cannon | 32732e3 | 2009-02-15 05:48:13 +0000 | [diff] [blame] | 1256 | If 'hooks' is false then use sys.path_hooks. |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1257 | |
| 1258 | """ |
Brett Cannon | e0d88a1 | 2012-04-25 20:54:04 -0400 | [diff] [blame] | 1259 | if not sys.path_hooks: |
| 1260 | _warnings.warn('sys.path_hooks is empty', ImportWarning) |
| 1261 | for hook in sys.path_hooks: |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1262 | try: |
| 1263 | return hook(path) |
| 1264 | except ImportError: |
| 1265 | continue |
| 1266 | else: |
Brett Cannon | aa93642 | 2012-04-27 15:30:58 -0400 | [diff] [blame] | 1267 | return None |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1268 | |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 1269 | @classmethod |
Brett Cannon | e0d88a1 | 2012-04-25 20:54:04 -0400 | [diff] [blame] | 1270 | def _path_importer_cache(cls, path): |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 1271 | """Get the finder for the path entry from sys.path_importer_cache. |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1272 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 1273 | If the path entry is not in the cache, find the appropriate finder |
| 1274 | and cache it. If no finder is available, store None. |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1275 | |
| 1276 | """ |
Brett Cannon | f58d45c | 2012-02-16 18:12:00 -0500 | [diff] [blame] | 1277 | if path == '': |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 1278 | path = '.' |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1279 | try: |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 1280 | finder = sys.path_importer_cache[path] |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1281 | except KeyError: |
Brett Cannon | f58d45c | 2012-02-16 18:12:00 -0500 | [diff] [blame] | 1282 | finder = cls._path_hooks(path) |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1283 | sys.path_importer_cache[path] = finder |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1284 | return finder |
| 1285 | |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 1286 | @classmethod |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 1287 | def _get_loader(cls, fullname, path): |
| 1288 | """Find the loader or namespace_path for this module/package name.""" |
| 1289 | # If this ends up being a namespace package, namespace_path is |
| 1290 | # the list of paths that will become its __path__ |
| 1291 | namespace_path = [] |
| 1292 | for entry in path: |
Barry Warsaw | 82c1c78 | 2012-11-20 15:22:51 -0500 | [diff] [blame] | 1293 | if not isinstance(entry, (str, bytes)): |
| 1294 | continue |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 1295 | finder = cls._path_importer_cache(entry) |
| 1296 | if finder is not None: |
| 1297 | if hasattr(finder, 'find_loader'): |
| 1298 | loader, portions = finder.find_loader(fullname) |
| 1299 | else: |
| 1300 | loader = finder.find_module(fullname) |
| 1301 | portions = [] |
| 1302 | if loader is not None: |
| 1303 | # We found a loader: return it immediately. |
Brett Cannon | f4dc920 | 2012-08-10 12:21:12 -0400 | [diff] [blame] | 1304 | return loader, namespace_path |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 1305 | # This is possibly part of a namespace package. |
| 1306 | # Remember these path entries (if any) for when we |
| 1307 | # create a namespace package, and continue iterating |
| 1308 | # on path. |
| 1309 | namespace_path.extend(portions) |
| 1310 | else: |
Brett Cannon | f4dc920 | 2012-08-10 12:21:12 -0400 | [diff] [blame] | 1311 | return None, namespace_path |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 1312 | |
| 1313 | @classmethod |
Brett Cannon | f7e5a8c | 2009-02-05 02:52:18 +0000 | [diff] [blame] | 1314 | def find_module(cls, fullname, path=None): |
Brett Cannon | 7aa21f7 | 2009-03-15 00:53:05 +0000 | [diff] [blame] | 1315 | """Find the module on sys.path or 'path' based on sys.path_hooks and |
| 1316 | sys.path_importer_cache.""" |
Brett Cannon | 7bd329d | 2012-04-17 21:41:35 -0400 | [diff] [blame] | 1317 | if path is None: |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1318 | path = sys.path |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 1319 | loader, namespace_path = cls._get_loader(fullname, path) |
| 1320 | if loader is not None: |
| 1321 | return loader |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1322 | else: |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 1323 | if namespace_path: |
| 1324 | # We found at least one namespace path. Return a |
| 1325 | # loader which can create the namespace package. |
| 1326 | return NamespaceLoader(fullname, namespace_path, cls._get_loader) |
| 1327 | else: |
| 1328 | return None |
Brett Cannon | 1d37668 | 2009-02-02 19:19:36 +0000 | [diff] [blame] | 1329 | |
| 1330 | |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 1331 | class FileFinder: |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1332 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1333 | """File-based finder. |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1334 | |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 1335 | Interactions with the file system are cached for performance, being |
| 1336 | refreshed when the directory the finder is handling has been modified. |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1337 | |
| 1338 | """ |
| 1339 | |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1340 | def __init__(self, path, *details): |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 1341 | """Initialize with the path to search on and a variable number of |
Eric Snow | 5b49962 | 2013-02-16 22:23:48 -0700 | [diff] [blame] | 1342 | 2-tuples containing the loader and the file suffixes the loader |
| 1343 | recognizes.""" |
Brett Cannon | ac9f2f3 | 2012-08-10 13:47:54 -0400 | [diff] [blame] | 1344 | loaders = [] |
| 1345 | for loader, suffixes in details: |
| 1346 | loaders.extend((suffix, loader) for suffix in suffixes) |
| 1347 | self._loaders = loaders |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 1348 | # Base (directory) path |
| 1349 | self.path = path or '.' |
| 1350 | self._path_mtime = -1 |
| 1351 | self._path_cache = set() |
Antoine Pitrou | b5c793a | 2012-02-20 22:06:59 +0100 | [diff] [blame] | 1352 | self._relaxed_path_cache = set() |
Brett Cannon | b46a179 | 2012-02-27 18:15:42 -0500 | [diff] [blame] | 1353 | |
| 1354 | def invalidate_caches(self): |
| 1355 | """Invalidate the directory mtime.""" |
| 1356 | self._path_mtime = -1 |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1357 | |
Brett Cannon | f410ce8 | 2012-08-10 17:41:23 -0400 | [diff] [blame] | 1358 | find_module = _find_module_shim |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 1359 | |
| 1360 | def find_loader(self, fullname): |
| 1361 | """Try to find a loader for the specified module, or the namespace |
| 1362 | package portions. Returns (loader, list-of-portions).""" |
Eric V. Smith | e51a369 | 2012-06-24 19:13:55 -0400 | [diff] [blame] | 1363 | is_namespace = False |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1364 | tail_module = fullname.rpartition('.')[2] |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 1365 | try: |
| 1366 | mtime = _os.stat(self.path).st_mtime |
| 1367 | except OSError: |
| 1368 | mtime = -1 |
Brett Cannon | b46a179 | 2012-02-27 18:15:42 -0500 | [diff] [blame] | 1369 | if mtime != self._path_mtime: |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 1370 | self._fill_cache() |
| 1371 | self._path_mtime = mtime |
Antoine Pitrou | b5c793a | 2012-02-20 22:06:59 +0100 | [diff] [blame] | 1372 | # tail_module keeps the original casing, for __file__ and friends |
| 1373 | if _relax_case(): |
| 1374 | cache = self._relaxed_path_cache |
| 1375 | cache_module = tail_module.lower() |
| 1376 | else: |
| 1377 | cache = self._path_cache |
| 1378 | cache_module = tail_module |
Brett Cannon | 44590e4 | 2012-04-14 18:37:07 -0400 | [diff] [blame] | 1379 | # Check if the module is the name of a directory (and thus a package). |
Antoine Pitrou | b5c793a | 2012-02-20 22:06:59 +0100 | [diff] [blame] | 1380 | if cache_module in cache: |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 1381 | base_path = _path_join(self.path, tail_module) |
| 1382 | if _path_isdir(base_path): |
Brett Cannon | ac9f2f3 | 2012-08-10 13:47:54 -0400 | [diff] [blame] | 1383 | for suffix, loader in self._loaders: |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 1384 | init_filename = '__init__' + suffix |
| 1385 | full_path = _path_join(base_path, init_filename) |
| 1386 | if _path_isfile(full_path): |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 1387 | return (loader(fullname, full_path), [base_path]) |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 1388 | else: |
Eric V. Smith | e51a369 | 2012-06-24 19:13:55 -0400 | [diff] [blame] | 1389 | # A namespace package, return the path if we don't also |
| 1390 | # find a module in the next section. |
| 1391 | is_namespace = True |
Brett Cannon | 44590e4 | 2012-04-14 18:37:07 -0400 | [diff] [blame] | 1392 | # Check for a file w/ a proper suffix exists. |
Brett Cannon | ac9f2f3 | 2012-08-10 13:47:54 -0400 | [diff] [blame] | 1393 | for suffix, loader in self._loaders: |
Brett Cannon | f8ffec0 | 2013-04-01 13:10:51 -0400 | [diff] [blame] | 1394 | full_path = _path_join(self.path, tail_module + suffix) |
| 1395 | _verbose_message('trying {}'.format(full_path), verbosity=2) |
Antoine Pitrou | b5c793a | 2012-02-20 22:06:59 +0100 | [diff] [blame] | 1396 | if cache_module + suffix in cache: |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 1397 | if _path_isfile(full_path): |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 1398 | return (loader(fullname, full_path), []) |
Eric V. Smith | e51a369 | 2012-06-24 19:13:55 -0400 | [diff] [blame] | 1399 | if is_namespace: |
Brett Cannon | f8ffec0 | 2013-04-01 13:10:51 -0400 | [diff] [blame] | 1400 | _verbose_message('possible namespace for {}'.format(base_path)) |
Eric V. Smith | e51a369 | 2012-06-24 19:13:55 -0400 | [diff] [blame] | 1401 | return (None, [base_path]) |
Eric V. Smith | 984b11f | 2012-05-24 20:21:04 -0400 | [diff] [blame] | 1402 | return (None, []) |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1403 | |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 1404 | def _fill_cache(self): |
| 1405 | """Fill the cache of potential modules and packages for this directory.""" |
| 1406 | path = self.path |
Nick Coghlan | 48fec05 | 2012-08-20 13:18:15 +1000 | [diff] [blame] | 1407 | try: |
| 1408 | contents = _os.listdir(path) |
Brett Cannon | a9976b3 | 2013-01-11 15:40:12 -0500 | [diff] [blame] | 1409 | except (FileNotFoundError, PermissionError, NotADirectoryError): |
| 1410 | # Directory has either been removed, turned into a file, or made |
| 1411 | # unreadable. |
Nick Coghlan | 48fec05 | 2012-08-20 13:18:15 +1000 | [diff] [blame] | 1412 | contents = [] |
Antoine Pitrou | b5c793a | 2012-02-20 22:06:59 +0100 | [diff] [blame] | 1413 | # We store two cached versions, to handle runtime changes of the |
| 1414 | # PYTHONCASEOK environment variable. |
Brett Cannon | 8ff6baf | 2012-04-20 12:53:14 -0400 | [diff] [blame] | 1415 | if not sys.platform.startswith('win'): |
| 1416 | self._path_cache = set(contents) |
| 1417 | else: |
| 1418 | # Windows users can import modules with case-insensitive file |
| 1419 | # suffixes (for legacy reasons). Make the suffix lowercase here |
| 1420 | # so it's done once instead of for every import. This is safe as |
| 1421 | # the specified suffixes to check against are always specified in a |
| 1422 | # case-sensitive manner. |
| 1423 | lower_suffix_contents = set() |
| 1424 | for item in contents: |
| 1425 | name, dot, suffix = item.partition('.') |
| 1426 | if dot: |
| 1427 | new_name = '{}.{}'.format(name, suffix.lower()) |
| 1428 | else: |
| 1429 | new_name = name |
| 1430 | lower_suffix_contents.add(new_name) |
| 1431 | self._path_cache = lower_suffix_contents |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 1432 | if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS): |
Serhiy Storchaka | 39e47f9 | 2013-02-25 15:40:33 +0200 | [diff] [blame] | 1433 | self._relaxed_path_cache = {fn.lower() for fn in contents} |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 1434 | |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 1435 | @classmethod |
| 1436 | def path_hook(cls, *loader_details): |
| 1437 | """A class method which returns a closure to use on sys.path_hook |
| 1438 | which will return an instance using the specified loaders and the path |
| 1439 | called on the closure. |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 1440 | |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 1441 | If the path called on the closure is not a directory, ImportError is |
| 1442 | raised. |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1443 | |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 1444 | """ |
| 1445 | def path_hook_for_FileFinder(path): |
| 1446 | """Path hook for importlib.machinery.FileFinder.""" |
| 1447 | if not _path_isdir(path): |
| 1448 | raise ImportError("only directories are supported", path=path) |
| 1449 | return cls(path, *loader_details) |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1450 | |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 1451 | return path_hook_for_FileFinder |
Brett Cannon | 61b1425 | 2010-07-03 21:48:25 +0000 | [diff] [blame] | 1452 | |
Antoine Pitrou | 310f95b | 2012-06-23 02:12:56 +0200 | [diff] [blame] | 1453 | def __repr__(self): |
Brett Cannon | 6072e0b | 2012-10-12 10:00:34 -0400 | [diff] [blame] | 1454 | return "FileFinder({!r})".format(self.path) |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1455 | |
| 1456 | |
Brett Cannon | ce43ddf | 2009-03-12 22:28:55 +0000 | [diff] [blame] | 1457 | # Import itself ############################################################### |
| 1458 | |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1459 | class _ImportLockContext: |
| 1460 | |
| 1461 | """Context manager for the import lock.""" |
| 1462 | |
| 1463 | def __enter__(self): |
| 1464 | """Acquire the import lock.""" |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1465 | _imp.acquire_lock() |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1466 | |
| 1467 | def __exit__(self, exc_type, exc_value, exc_traceback): |
| 1468 | """Release the import lock regardless of any raised exceptions.""" |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1469 | _imp.release_lock() |
Brett Cannon | e9103d2 | 2009-03-12 22:37:06 +0000 | [diff] [blame] | 1470 | |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 1471 | |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1472 | def _resolve_name(name, package, level): |
| 1473 | """Resolve a relative module name to an absolute one.""" |
Philip Jenvey | 4b42ff6 | 2012-02-24 21:48:17 -0800 | [diff] [blame] | 1474 | bits = package.rsplit('.', level - 1) |
Brett Cannon | 625cd23 | 2012-02-24 11:20:54 -0500 | [diff] [blame] | 1475 | if len(bits) < level: |
| 1476 | raise ValueError('attempted relative import beyond top-level package') |
| 1477 | base = bits[0] |
Florent Xicluna | 79d79a0 | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 1478 | return '{}.{}'.format(base, name) if name else base |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1479 | |
| 1480 | |
| 1481 | def _find_module(name, path): |
| 1482 | """Find a module's loader.""" |
Brett Cannon | ce418b4 | 2012-04-27 14:01:58 -0400 | [diff] [blame] | 1483 | if not sys.meta_path: |
| 1484 | _warnings.warn('sys.meta_path is empty', ImportWarning) |
| 1485 | for finder in sys.meta_path: |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 1486 | with _ImportLockContext(): |
| 1487 | loader = finder.find_module(name, path) |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1488 | if loader is not None: |
| 1489 | # The parent import may have already imported this module. |
| 1490 | if name not in sys.modules: |
| 1491 | return loader |
| 1492 | else: |
| 1493 | return sys.modules[name].__loader__ |
| 1494 | else: |
| 1495 | return None |
| 1496 | |
| 1497 | |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1498 | def _sanity_check(name, package, level): |
| 1499 | """Verify arguments are "sane".""" |
Brett Cannon | 068915c | 2012-02-23 18:18:48 -0500 | [diff] [blame] | 1500 | if not isinstance(name, str): |
Brett Cannon | 34d8e41 | 2012-02-22 18:33:05 -0500 | [diff] [blame] | 1501 | raise TypeError("module name must be str, not {}".format(type(name))) |
| 1502 | if level < 0: |
| 1503 | raise ValueError('level must be >= 0') |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1504 | if package: |
Brett Cannon | 068915c | 2012-02-23 18:18:48 -0500 | [diff] [blame] | 1505 | if not isinstance(package, str): |
Brett Cannon | f500778 | 2012-02-23 18:29:12 -0500 | [diff] [blame] | 1506 | raise TypeError("__package__ not set to a string") |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1507 | elif package not in sys.modules: |
Florent Xicluna | 79d79a0 | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 1508 | msg = ("Parent module {!r} not loaded, cannot perform relative " |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1509 | "import") |
| 1510 | raise SystemError(msg.format(package)) |
| 1511 | if not name and level == 0: |
| 1512 | raise ValueError("Empty module name") |
| 1513 | |
| 1514 | |
Brett Cannon | 34d8e41 | 2012-02-22 18:33:05 -0500 | [diff] [blame] | 1515 | _ERR_MSG = 'No module named {!r}' |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1516 | |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 1517 | def _find_and_load_unlocked(name, import_): |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1518 | path = None |
| 1519 | parent = name.rpartition('.')[0] |
| 1520 | if parent: |
| 1521 | if parent not in sys.modules: |
Nick Coghlan | 42c0766 | 2012-07-31 21:14:18 +1000 | [diff] [blame] | 1522 | _call_with_frames_removed(import_, parent) |
Brett Cannon | 927d874 | 2012-04-02 20:33:56 -0400 | [diff] [blame] | 1523 | # Crazy side-effects! |
| 1524 | if name in sys.modules: |
| 1525 | return sys.modules[name] |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1526 | # Backwards-compatibility; be nicer to skip the dict lookup. |
| 1527 | parent_module = sys.modules[parent] |
| 1528 | try: |
| 1529 | path = parent_module.__path__ |
| 1530 | except AttributeError: |
| 1531 | msg = (_ERR_MSG + '; {} is not a package').format(name, parent) |
Brett Cannon | bbb6680 | 2012-04-12 21:09:01 -0400 | [diff] [blame] | 1532 | raise ImportError(msg, name=name) |
Brett Cannon | 34d8e41 | 2012-02-22 18:33:05 -0500 | [diff] [blame] | 1533 | loader = _find_module(name, path) |
| 1534 | if loader is None: |
Brett Cannon | 12c6bda | 2012-08-24 18:25:59 -0400 | [diff] [blame] | 1535 | exc = ImportError(_ERR_MSG.format(name), name=name) |
| 1536 | # TODO(brett): switch to a proper ModuleNotFound exception in Python |
| 1537 | # 3.4. |
| 1538 | exc._not_found = True |
| 1539 | raise exc |
Benjamin Peterson | d76bc7a | 2012-04-18 10:55:43 -0400 | [diff] [blame] | 1540 | elif name not in sys.modules: |
| 1541 | # The parent import may have already imported this module. |
| 1542 | loader.load_module(name) |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 1543 | _verbose_message('import {!r} # {!r}', name, loader) |
Benjamin Peterson | d76bc7a | 2012-04-18 10:55:43 -0400 | [diff] [blame] | 1544 | # Backwards-compatibility; be nicer to skip the dict lookup. |
| 1545 | module = sys.modules[name] |
Brett Cannon | 34d8e41 | 2012-02-22 18:33:05 -0500 | [diff] [blame] | 1546 | if parent: |
| 1547 | # Set the module as an attribute on its parent. |
| 1548 | parent_module = sys.modules[parent] |
| 1549 | setattr(parent_module, name.rpartition('.')[2], module) |
| 1550 | # Set __package__ if the loader did not. |
Florent Xicluna | 79d79a0 | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 1551 | if getattr(module, '__package__', None) is None: |
Brett Cannon | 34d8e41 | 2012-02-22 18:33:05 -0500 | [diff] [blame] | 1552 | try: |
| 1553 | module.__package__ = module.__name__ |
| 1554 | if not hasattr(module, '__path__'): |
| 1555 | module.__package__ = module.__package__.rpartition('.')[0] |
| 1556 | except AttributeError: |
| 1557 | pass |
Brett Cannon | efad00d | 2012-04-27 17:27:14 -0400 | [diff] [blame] | 1558 | # Set loader if need be. |
Brett Cannon | 4802bec | 2013-03-13 10:41:36 -0700 | [diff] [blame] | 1559 | if getattr(module, '__loader__', None) is None: |
Brett Cannon | efad00d | 2012-04-27 17:27:14 -0400 | [diff] [blame] | 1560 | try: |
| 1561 | module.__loader__ = loader |
| 1562 | except AttributeError: |
| 1563 | pass |
Brett Cannon | 34d8e41 | 2012-02-22 18:33:05 -0500 | [diff] [blame] | 1564 | return module |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1565 | |
| 1566 | |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 1567 | def _find_and_load(name, import_): |
| 1568 | """Find and load the module, and release the import lock.""" |
| 1569 | try: |
| 1570 | lock = _get_module_lock(name) |
| 1571 | finally: |
| 1572 | _imp.release_lock() |
| 1573 | lock.acquire() |
| 1574 | try: |
| 1575 | return _find_and_load_unlocked(name, import_) |
| 1576 | finally: |
| 1577 | lock.release() |
| 1578 | |
| 1579 | |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 1580 | def _gcd_import(name, package=None, level=0): |
| 1581 | """Import and return the module based on its name, the package the call is |
| 1582 | being made from, and the level adjustment. |
| 1583 | |
| 1584 | This function represents the greatest common denominator of functionality |
Eric V. Smith | 4169826 | 2011-03-14 10:56:33 -0400 | [diff] [blame] | 1585 | between import_module and __import__. This includes setting __package__ if |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 1586 | the loader did not. |
| 1587 | |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 1588 | """ |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1589 | _sanity_check(name, package, level) |
Brett Cannon | 7f9876c | 2009-02-06 02:47:33 +0000 | [diff] [blame] | 1590 | if level > 0: |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1591 | name = _resolve_name(name, package, level) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 1592 | _imp.acquire_lock() |
| 1593 | if name not in sys.modules: |
Brett Cannon | 34d8e41 | 2012-02-22 18:33:05 -0500 | [diff] [blame] | 1594 | return _find_and_load(name, _gcd_import) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 1595 | module = sys.modules[name] |
| 1596 | if module is None: |
| 1597 | _imp.release_lock() |
| 1598 | message = ("import of {} halted; " |
| 1599 | "None in sys.modules".format(name)) |
| 1600 | raise ImportError(message, name=name) |
| 1601 | _lock_unlock_module(name) |
| 1602 | return module |
Brett Cannon | 23cbd8a | 2009-01-18 00:24:28 +0000 | [diff] [blame] | 1603 | |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1604 | def _handle_fromlist(module, fromlist, import_): |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1605 | """Figure out what __import__ should return. |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 1606 | |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1607 | The import_ parameter is a callable which takes the name of module to |
| 1608 | import. It is required to decouple the function from assuming importlib's |
| 1609 | import implementation is desired. |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 1610 | |
| 1611 | """ |
Brett Cannon | 2c318a1 | 2009-02-07 01:15:27 +0000 | [diff] [blame] | 1612 | # The hell that is fromlist ... |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1613 | # If a package was imported, try to import stuff from fromlist. |
| 1614 | if hasattr(module, '__path__'): |
Brett Cannon | 461c813 | 2012-07-10 10:05:00 -0400 | [diff] [blame] | 1615 | if '*' in fromlist: |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1616 | fromlist = list(fromlist) |
| 1617 | fromlist.remove('*') |
Brett Cannon | 461c813 | 2012-07-10 10:05:00 -0400 | [diff] [blame] | 1618 | if hasattr(module, '__all__'): |
| 1619 | fromlist.extend(module.__all__) |
Florent Xicluna | 79d79a0 | 2012-07-07 13:16:44 +0200 | [diff] [blame] | 1620 | for x in fromlist: |
| 1621 | if not hasattr(module, x): |
Brett Cannon | a6ce4fd | 2012-10-10 19:03:46 -0400 | [diff] [blame] | 1622 | from_name = '{}.{}'.format(module.__name__, x) |
Brett Cannon | 7385adc | 2012-08-17 13:21:16 -0400 | [diff] [blame] | 1623 | try: |
Brett Cannon | a6ce4fd | 2012-10-10 19:03:46 -0400 | [diff] [blame] | 1624 | _call_with_frames_removed(import_, from_name) |
Brett Cannon | 12c6bda | 2012-08-24 18:25:59 -0400 | [diff] [blame] | 1625 | except ImportError as exc: |
Brett Cannon | 7385adc | 2012-08-17 13:21:16 -0400 | [diff] [blame] | 1626 | # Backwards-compatibility dictates we ignore failed |
Brett Cannon | 12c6bda | 2012-08-24 18:25:59 -0400 | [diff] [blame] | 1627 | # imports triggered by fromlist for modules that don't |
| 1628 | # exist. |
| 1629 | # TODO(brett): In Python 3.4, have import raise |
| 1630 | # ModuleNotFound and catch that. |
Brett Cannon | a6ce4fd | 2012-10-10 19:03:46 -0400 | [diff] [blame] | 1631 | if getattr(exc, '_not_found', False): |
| 1632 | if exc.name == from_name: |
| 1633 | continue |
| 1634 | raise |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1635 | return module |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1636 | |
| 1637 | |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1638 | def _calc___package__(globals): |
| 1639 | """Calculate what __package__ should be. |
| 1640 | |
| 1641 | __package__ is not guaranteed to be defined or could be set to None |
| 1642 | to represent that its proper value is unknown. |
| 1643 | |
| 1644 | """ |
| 1645 | package = globals.get('__package__') |
| 1646 | if package is None: |
| 1647 | package = globals['__name__'] |
| 1648 | if '__path__' not in globals: |
| 1649 | package = package.rpartition('.')[0] |
| 1650 | return package |
| 1651 | |
| 1652 | |
Martin v. Löwis | e3010a8 | 2012-07-28 21:33:05 +0200 | [diff] [blame] | 1653 | def _get_supported_file_loaders(): |
| 1654 | """Returns a list of file-based module loaders. |
| 1655 | |
| 1656 | Each item is a tuple (loader, suffixes, allow_packages). |
| 1657 | """ |
Brett Cannon | ac9f2f3 | 2012-08-10 13:47:54 -0400 | [diff] [blame] | 1658 | extensions = ExtensionFileLoader, _imp.extension_suffixes() |
| 1659 | source = SourceFileLoader, SOURCE_SUFFIXES |
| 1660 | bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES |
Martin v. Löwis | e3010a8 | 2012-07-28 21:33:05 +0200 | [diff] [blame] | 1661 | return [extensions, source, bytecode] |
| 1662 | |
| 1663 | |
Brett Cannon | cb4996a | 2012-08-06 16:34:44 -0400 | [diff] [blame] | 1664 | def __import__(name, globals=None, locals=None, fromlist=(), level=0): |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1665 | """Import a module. |
| 1666 | |
| 1667 | The 'globals' argument is used to infer where the import is occuring from |
| 1668 | to handle relative imports. The 'locals' argument is ignored. The |
| 1669 | 'fromlist' argument specifies what should exist as attributes on the module |
| 1670 | being imported (e.g. ``from module import <fromlist>``). The 'level' |
| 1671 | argument represents the package location to import from in a relative |
| 1672 | import (e.g. ``from ..pkg import mod`` would have a 'level' of 2). |
| 1673 | |
| 1674 | """ |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1675 | if level == 0: |
| 1676 | module = _gcd_import(name) |
| 1677 | else: |
Brett Cannon | cb4996a | 2012-08-06 16:34:44 -0400 | [diff] [blame] | 1678 | globals_ = globals if globals is not None else {} |
| 1679 | package = _calc___package__(globals_) |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1680 | module = _gcd_import(name, package, level) |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1681 | if not fromlist: |
| 1682 | # Return up to the first dot in 'name'. This is complicated by the fact |
| 1683 | # that 'name' may be relative. |
| 1684 | if level == 0: |
Antoine Pitrou | 6efa50a | 2012-05-07 21:41:59 +0200 | [diff] [blame] | 1685 | return _gcd_import(name.partition('.')[0]) |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1686 | elif not name: |
| 1687 | return module |
| 1688 | else: |
Brett Cannon | 8ed677d | 2012-09-28 16:41:39 -0400 | [diff] [blame] | 1689 | # Figure out where to slice the module's name up to the first dot |
| 1690 | # in 'name'. |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1691 | cut_off = len(name) - len(name.partition('.')[0]) |
Brett Cannon | 8ed677d | 2012-09-28 16:41:39 -0400 | [diff] [blame] | 1692 | # Slice end needs to be positive to alleviate need to special-case |
| 1693 | # when ``'.' not in name``. |
Brett Cannon | 49f8d8b | 2012-04-14 21:50:00 -0400 | [diff] [blame] | 1694 | return sys.modules[module.__name__[:len(module.__name__)-cut_off]] |
Brett Cannon | 4b03b68 | 2012-02-23 20:47:57 -0500 | [diff] [blame] | 1695 | else: |
| 1696 | return _handle_fromlist(module, fromlist, _gcd_import) |
Brett Cannon | 7fab676 | 2012-02-16 13:43:41 -0500 | [diff] [blame] | 1697 | |
| 1698 | |
Brett Cannon | 24117a7 | 2012-04-20 18:04:03 -0400 | [diff] [blame] | 1699 | |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1700 | def _setup(sys_module, _imp_module): |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1701 | """Setup importlib by importing needed built-in modules and injecting them |
| 1702 | into the global namespace. |
| 1703 | |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1704 | As sys is needed for sys.modules access and _imp is needed to load built-in |
Brett Cannon | 0568d6f | 2012-02-14 18:38:11 -0500 | [diff] [blame] | 1705 | modules, those two modules must be explicitly passed in. |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1706 | |
| 1707 | """ |
Benjamin Peterson | feaa54f | 2012-09-25 11:22:59 -0400 | [diff] [blame] | 1708 | global _imp, sys, BYTECODE_SUFFIXES |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1709 | _imp = _imp_module |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1710 | sys = sys_module |
| 1711 | |
Benjamin Peterson | feaa54f | 2012-09-25 11:22:59 -0400 | [diff] [blame] | 1712 | if sys.flags.optimize: |
| 1713 | BYTECODE_SUFFIXES = OPTIMIZED_BYTECODE_SUFFIXES |
| 1714 | else: |
| 1715 | BYTECODE_SUFFIXES = DEBUG_BYTECODE_SUFFIXES |
| 1716 | |
Brett Cannon | 0ecd30b | 2013-02-01 14:04:12 -0500 | [diff] [blame] | 1717 | module_type = type(sys) |
Brett Cannon | da9cf0e | 2013-02-01 15:31:49 -0500 | [diff] [blame] | 1718 | for name, module in sys.modules.items(): |
Brett Cannon | 0ecd30b | 2013-02-01 14:04:12 -0500 | [diff] [blame] | 1719 | if isinstance(module, module_type): |
| 1720 | if not hasattr(module, '__loader__'): |
Brett Cannon | da9cf0e | 2013-02-01 15:31:49 -0500 | [diff] [blame] | 1721 | if name in sys.builtin_module_names: |
| 1722 | module.__loader__ = BuiltinImporter |
| 1723 | elif _imp.is_frozen(name): |
| 1724 | module.__loader__ = FrozenImporter |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1725 | |
| 1726 | self_module = sys.modules[__name__] |
| 1727 | for builtin_name in ('_io', '_warnings', 'builtins', 'marshal'): |
| 1728 | if builtin_name not in sys.modules: |
| 1729 | builtin_module = BuiltinImporter.load_module(builtin_name) |
| 1730 | else: |
| 1731 | builtin_module = sys.modules[builtin_name] |
| 1732 | setattr(self_module, builtin_name, builtin_module) |
| 1733 | |
Jesus Cea | 4791a24 | 2012-10-05 03:15:39 +0200 | [diff] [blame] | 1734 | os_details = ('posix', ['/']), ('nt', ['\\', '/']) |
Brett Cannon | ed672d6 | 2012-04-20 21:19:53 -0400 | [diff] [blame] | 1735 | for builtin_os, path_separators in os_details: |
Brett Cannon | 5c903e6 | 2012-04-22 11:45:07 -0400 | [diff] [blame] | 1736 | # Assumption made in _path_join() |
| 1737 | assert all(len(sep) == 1 for sep in path_separators) |
Brett Cannon | ed672d6 | 2012-04-20 21:19:53 -0400 | [diff] [blame] | 1738 | path_sep = path_separators[0] |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1739 | if builtin_os in sys.modules: |
| 1740 | os_module = sys.modules[builtin_os] |
| 1741 | break |
| 1742 | else: |
| 1743 | try: |
| 1744 | os_module = BuiltinImporter.load_module(builtin_os) |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1745 | break |
| 1746 | except ImportError: |
| 1747 | continue |
| 1748 | else: |
| 1749 | raise ImportError('importlib requires posix or nt') |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 1750 | |
| 1751 | try: |
| 1752 | thread_module = BuiltinImporter.load_module('_thread') |
| 1753 | except ImportError: |
| 1754 | # Python was built without threads |
| 1755 | thread_module = None |
| 1756 | weakref_module = BuiltinImporter.load_module('_weakref') |
| 1757 | |
Martin v. Löwis | e3010a8 | 2012-07-28 21:33:05 +0200 | [diff] [blame] | 1758 | if builtin_os == 'nt': |
| 1759 | winreg_module = BuiltinImporter.load_module('winreg') |
| 1760 | setattr(self_module, '_winreg', winreg_module) |
| 1761 | |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1762 | setattr(self_module, '_os', os_module) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 1763 | setattr(self_module, '_thread', thread_module) |
| 1764 | setattr(self_module, '_weakref', weakref_module) |
Brett Cannon | 354c26e | 2012-02-08 18:50:22 -0500 | [diff] [blame] | 1765 | setattr(self_module, 'path_sep', path_sep) |
Serhiy Storchaka | 39e47f9 | 2013-02-25 15:40:33 +0200 | [diff] [blame] | 1766 | setattr(self_module, 'path_separators', ''.join(path_separators)) |
Antoine Pitrou | c541f8e | 2012-02-20 01:48:16 +0100 | [diff] [blame] | 1767 | # Constants |
Antoine Pitrou | b67075b | 2012-02-20 13:52:47 +0100 | [diff] [blame] | 1768 | setattr(self_module, '_relax_case', _make_relax_case()) |
Brett Cannon | ac9f2f3 | 2012-08-10 13:47:54 -0400 | [diff] [blame] | 1769 | EXTENSION_SUFFIXES.extend(_imp.extension_suffixes()) |
Brett Cannon | a64faf0 | 2012-04-21 18:52:52 -0400 | [diff] [blame] | 1770 | if builtin_os == 'nt': |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 1771 | SOURCE_SUFFIXES.append('.pyw') |
Brett Cannon | ac9f2f3 | 2012-08-10 13:47:54 -0400 | [diff] [blame] | 1772 | if '_d.pyd' in EXTENSION_SUFFIXES: |
Nick Coghlan | ff79486 | 2012-08-02 21:45:24 +1000 | [diff] [blame] | 1773 | WindowsRegistryFinder.DEBUG_BUILD = True |
Brett Cannon | f2e8675 | 2012-02-17 09:46:48 -0500 | [diff] [blame] | 1774 | |
Brett Cannon | 0568d6f | 2012-02-14 18:38:11 -0500 | [diff] [blame] | 1775 | |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1776 | def _install(sys_module, _imp_module): |
Brett Cannon | feccc09 | 2012-05-04 16:47:54 -0400 | [diff] [blame] | 1777 | """Install importlib as the implementation of import.""" |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1778 | _setup(sys_module, _imp_module) |
Martin v. Löwis | e3010a8 | 2012-07-28 21:33:05 +0200 | [diff] [blame] | 1779 | supported_loaders = _get_supported_file_loaders() |
Brett Cannon | aa93642 | 2012-04-27 15:30:58 -0400 | [diff] [blame] | 1780 | sys.path_hooks.extend([FileFinder.path_hook(*supported_loaders)]) |
Martin v. Löwis | e3010a8 | 2012-07-28 21:33:05 +0200 | [diff] [blame] | 1781 | sys.meta_path.append(BuiltinImporter) |
| 1782 | sys.meta_path.append(FrozenImporter) |
| 1783 | if _os.__name__ == 'nt': |
Nick Coghlan | ff79486 | 2012-08-02 21:45:24 +1000 | [diff] [blame] | 1784 | sys.meta_path.append(WindowsRegistryFinder) |
Martin v. Löwis | e3010a8 | 2012-07-28 21:33:05 +0200 | [diff] [blame] | 1785 | sys.meta_path.append(PathFinder) |