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