blob: 99d8ff71b0c778192766653f8db8ca267ca0aa19 [file] [log] [blame]
Brett Cannon6f44d662012-04-15 16:08:47 -04001"""This module provides the components needed to build your own __import__
2function. Undocumented functions are obsolete.
3
4In most cases it is preferred you consider using the importlib module's
5functionality over this module.
6
7"""
8# (Probably) need to stay in _imp
9from _imp import (lock_held, acquire_lock, release_lock, reload,
Brett Cannon2fef4d22012-04-15 19:06:23 -040010 load_dynamic, get_frozen_object, is_frozen_package,
11 init_builtin, init_frozen, is_builtin, is_frozen,
12 _fix_co_filename)
Brett Cannon24117a72012-04-20 18:04:03 -040013# Could move out of _imp, but not worth the code
14from _imp import get_magic
Brett Cannonea59dbf2012-04-20 21:44:46 -040015# Can (probably) move to importlib
16from _imp import (get_tag, get_suffixes, source_from_cache)
Brett Cannon6f44d662012-04-15 16:08:47 -040017# Should be re-implemented here (and mostly deprecated)
Brett Cannon64befe92012-04-17 19:14:26 -040018from _imp import (find_module, NullImporter,
Brett Cannon6f44d662012-04-15 16:08:47 -040019 SEARCH_ERROR, PY_SOURCE, PY_COMPILED, C_EXTENSION,
20 PY_RESOURCE, PKG_DIRECTORY, C_BUILTIN, PY_FROZEN,
21 PY_CODERESOURCE, IMP_HOOK)
22
23from importlib._bootstrap import _new_module as new_module
Brett Cannonea59dbf2012-04-20 21:44:46 -040024from importlib._bootstrap import _cache_from_source as cache_from_source
Brett Cannon01a76172012-04-15 20:25:23 -040025
Brett Cannon2ee61422012-04-15 22:28:28 -040026from importlib import _bootstrap
27import os
28
29
Brett Cannon64befe92012-04-17 19:14:26 -040030class _HackedGetData:
Brett Cannon16475ad2012-04-16 22:11:25 -040031
Brett Cannon64befe92012-04-17 19:14:26 -040032 """Compatibiilty support for 'file' arguments of various load_*()
33 functions."""
Brett Cannon16475ad2012-04-16 22:11:25 -040034
35 def __init__(self, fullname, path, file=None):
36 super().__init__(fullname, path)
37 self.file = file
38
39 def get_data(self, path):
Brett Cannon64befe92012-04-17 19:14:26 -040040 """Gross hack to contort loader to deal w/ load_*()'s bad API."""
Brett Cannon578393b2012-04-16 23:11:28 -040041 if self.file and path == self._path:
Brett Cannon16475ad2012-04-16 22:11:25 -040042 with self.file:
43 # Technically should be returning bytes, but
44 # SourceLoader.get_code() just passed what is returned to
45 # compile() which can handle str. And converting to bytes would
46 # require figuring out the encoding to decode to and
47 # tokenize.detect_encoding() only accepts bytes.
48 return self.file.read()
49 else:
50 return super().get_data(path)
51
52
Brett Cannon64befe92012-04-17 19:14:26 -040053class _LoadSourceCompatibility(_HackedGetData, _bootstrap._SourceFileLoader):
54
55 """Compatibility support for implementing load_source()."""
56
57
Brett Cannon16475ad2012-04-16 22:11:25 -040058def load_source(name, pathname, file=None):
59 return _LoadSourceCompatibility(name, pathname, file).load_module(name)
60
61
Brett Cannon64befe92012-04-17 19:14:26 -040062class _LoadCompiledCompatibility(_HackedGetData,
63 _bootstrap._SourcelessFileLoader):
64
65 """Compatibility support for implementing load_compiled()."""
66
67
68def load_compiled(name, pathname, file=None):
69 return _LoadCompiledCompatibility(name, pathname, file).load_module(name)
70
71
Brett Cannon2ee61422012-04-15 22:28:28 -040072def load_package(name, path):
73 if os.path.isdir(path):
74 extensions = _bootstrap._suffix_list(PY_SOURCE)
75 extensions += _bootstrap._suffix_list(PY_COMPILED)
76 for extension in extensions:
77 path = os.path.join(path, '__init__'+extension)
78 if os.path.exists(path):
79 break
80 else:
81 raise ValueError('{!r} is not a package'.format(path))
82 return _bootstrap._SourceFileLoader(name, path).load_module(name)
83
Brett Cannon01a76172012-04-15 20:25:23 -040084
85def load_module(name, file, filename, details):
86 """Load a module, given information returned by find_module().
87
88 The module name must include the full package name, if any.
89
90 """
91 suffix, mode, type_ = details
Brett Cannonde10bf42012-04-16 20:44:21 -040092 if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
Brett Cannon01a76172012-04-15 20:25:23 -040093 raise ValueError('invalid file open mode {!r}'.format(mode))
94 elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
95 msg = 'file object required for import (type code {})'.format(type_)
96 raise ValueError(msg)
97 elif type_ == PY_SOURCE:
98 return load_source(name, filename, file)
99 elif type_ == PY_COMPILED:
100 return load_compiled(name, filename, file)
101 elif type_ == PKG_DIRECTORY:
102 return load_package(name, filename)
103 elif type_ == C_BUILTIN:
104 return init_builtin(name)
105 elif type_ == PY_FROZEN:
106 return init_frozen(name)
107 else:
108 msg = "Don't know how to import {} (type code {}".format(name, type_)
109 raise ImportError(msg, name=name)