Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1 | """This module provides the components needed to build your own __import__ |
| 2 | function. Undocumented functions are obsolete. |
| 3 | |
| 4 | In most cases it is preferred you consider using the importlib module's |
| 5 | functionality over this module. |
| 6 | |
| 7 | """ |
| 8 | # (Probably) need to stay in _imp |
| 9 | from _imp import (lock_held, acquire_lock, release_lock, reload, |
Brett Cannon | 2fef4d2 | 2012-04-15 19:06:23 -0400 | [diff] [blame] | 10 | load_dynamic, get_frozen_object, is_frozen_package, |
| 11 | init_builtin, init_frozen, is_builtin, is_frozen, |
| 12 | _fix_co_filename) |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 13 | # Can (probably) move to importlib |
| 14 | from _imp import (get_magic, get_tag, get_suffixes, cache_from_source, |
| 15 | source_from_cache) |
| 16 | # Should be re-implemented here (and mostly deprecated) |
Brett Cannon | 01a7617 | 2012-04-15 20:25:23 -0400 | [diff] [blame^] | 17 | from _imp import (find_module, load_compiled, |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 18 | load_package, load_source, NullImporter, |
| 19 | SEARCH_ERROR, PY_SOURCE, PY_COMPILED, C_EXTENSION, |
| 20 | PY_RESOURCE, PKG_DIRECTORY, C_BUILTIN, PY_FROZEN, |
| 21 | PY_CODERESOURCE, IMP_HOOK) |
| 22 | |
| 23 | from importlib._bootstrap import _new_module as new_module |
Brett Cannon | 01a7617 | 2012-04-15 20:25:23 -0400 | [diff] [blame^] | 24 | |
| 25 | |
| 26 | def load_module(name, file, filename, details): |
| 27 | """Load a module, given information returned by find_module(). |
| 28 | |
| 29 | The module name must include the full package name, if any. |
| 30 | |
| 31 | """ |
| 32 | suffix, mode, type_ = details |
| 33 | if mode and (not mode.startswith(('r', 'U'))) or '+' in mode: |
| 34 | raise ValueError('invalid file open mode {!r}'.format(mode)) |
| 35 | elif file is None and type_ in {PY_SOURCE, PY_COMPILED}: |
| 36 | msg = 'file object required for import (type code {})'.format(type_) |
| 37 | raise ValueError(msg) |
| 38 | elif type_ == PY_SOURCE: |
| 39 | return load_source(name, filename, file) |
| 40 | elif type_ == PY_COMPILED: |
| 41 | return load_compiled(name, filename, file) |
| 42 | elif type_ == PKG_DIRECTORY: |
| 43 | return load_package(name, filename) |
| 44 | elif type_ == C_BUILTIN: |
| 45 | return init_builtin(name) |
| 46 | elif type_ == PY_FROZEN: |
| 47 | return init_frozen(name) |
| 48 | else: |
| 49 | msg = "Don't know how to import {} (type code {}".format(name, type_) |
| 50 | raise ImportError(msg, name=name) |