Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

imp.py 10 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
  1. """This module provides the components needed to build your own __import__
  2. function. Undocumented functions are obsolete.
  3. In most cases it is preferred you consider using the importlib module's
  4. functionality over this module.
  5. """
  6. # (Probably) need to stay in _imp
  7. from _imp import (lock_held, acquire_lock, release_lock,
  8. get_frozen_object, is_frozen_package,
  9. init_frozen, is_builtin, is_frozen,
  10. _fix_co_filename)
  11. try:
  12. from _imp import create_dynamic
  13. except ImportError:
  14. # Platform doesn't support dynamic loading.
  15. create_dynamic = None
  16. from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name
  17. from importlib._bootstrap_external import SourcelessFileLoader
  18. from importlib import machinery
  19. from importlib import util
  20. import importlib
  21. import os
  22. import sys
  23. import tokenize
  24. import types
  25. import warnings
  26. warnings.warn("the imp module is deprecated in favour of importlib; "
  27. "see the module's documentation for alternative uses",
  28. DeprecationWarning, stacklevel=2)
  29. # DEPRECATED
  30. SEARCH_ERROR = 0
  31. PY_SOURCE = 1
  32. PY_COMPILED = 2
  33. C_EXTENSION = 3
  34. PY_RESOURCE = 4
  35. PKG_DIRECTORY = 5
  36. C_BUILTIN = 6
  37. PY_FROZEN = 7
  38. PY_CODERESOURCE = 8
  39. IMP_HOOK = 9
  40. def new_module(name):
  41. """**DEPRECATED**
  42. Create a new module.
  43. The module is not entered into sys.modules.
  44. """
  45. return types.ModuleType(name)
  46. def get_magic():
  47. """**DEPRECATED**
  48. Return the magic number for .pyc files.
  49. """
  50. return util.MAGIC_NUMBER
  51. def get_tag():
  52. """Return the magic tag for .pyc files."""
  53. return sys.implementation.cache_tag
  54. def cache_from_source(path, debug_override=None):
  55. """**DEPRECATED**
  56. Given the path to a .py file, return the path to its .pyc file.
  57. The .py file does not need to exist; this simply returns the path to the
  58. .pyc file calculated as if the .py file were imported.
  59. If debug_override is not None, then it must be a boolean and is used in
  60. place of sys.flags.optimize.
  61. If sys.implementation.cache_tag is None then NotImplementedError is raised.
  62. """
  63. with warnings.catch_warnings():
  64. warnings.simplefilter('ignore')
  65. return util.cache_from_source(path, debug_override)
  66. def source_from_cache(path):
  67. """**DEPRECATED**
  68. Given the path to a .pyc. file, return the path to its .py file.
  69. The .pyc file does not need to exist; this simply returns the path to
  70. the .py file calculated to correspond to the .pyc file. If path does
  71. not conform to PEP 3147 format, ValueError will be raised. If
  72. sys.implementation.cache_tag is None then NotImplementedError is raised.
  73. """
  74. return util.source_from_cache(path)
  75. def get_suffixes():
  76. """**DEPRECATED**"""
  77. extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES]
  78. source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
  79. bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
  80. return extensions + source + bytecode
  81. class NullImporter:
  82. """**DEPRECATED**
  83. Null import object.
  84. """
  85. def __init__(self, path):
  86. if path == '':
  87. raise ImportError('empty pathname', path='')
  88. elif os.path.isdir(path):
  89. raise ImportError('existing directory', path=path)
  90. def find_module(self, fullname):
  91. """Always returns None."""
  92. return None
  93. class _HackedGetData:
  94. """Compatibility support for 'file' arguments of various load_*()
  95. functions."""
  96. def __init__(self, fullname, path, file=None):
  97. super().__init__(fullname, path)
  98. self.file = file
  99. def get_data(self, path):
  100. """Gross hack to contort loader to deal w/ load_*()'s bad API."""
  101. if self.file and path == self.path:
  102. # The contract of get_data() requires us to return bytes. Reopen the
  103. # file in binary mode if needed.
  104. if not self.file.closed:
  105. file = self.file
  106. if 'b' not in file.mode:
  107. file.close()
  108. if self.file.closed:
  109. self.file = file = open(self.path, 'rb')
  110. with file:
  111. return file.read()
  112. else:
  113. return super().get_data(path)
  114. class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader):
  115. """Compatibility support for implementing load_source()."""
  116. def load_source(name, pathname, file=None):
  117. loader = _LoadSourceCompatibility(name, pathname, file)
  118. spec = util.spec_from_file_location(name, pathname, loader=loader)
  119. if name in sys.modules:
  120. module = _exec(spec, sys.modules[name])
  121. else:
  122. module = _load(spec)
  123. # To allow reloading to potentially work, use a non-hacked loader which
  124. # won't rely on a now-closed file object.
  125. module.__loader__ = machinery.SourceFileLoader(name, pathname)
  126. module.__spec__.loader = module.__loader__
  127. return module
  128. class _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader):
  129. """Compatibility support for implementing load_compiled()."""
  130. def load_compiled(name, pathname, file=None):
  131. """**DEPRECATED**"""
  132. loader = _LoadCompiledCompatibility(name, pathname, file)
  133. spec = util.spec_from_file_location(name, pathname, loader=loader)
  134. if name in sys.modules:
  135. module = _exec(spec, sys.modules[name])
  136. else:
  137. module = _load(spec)
  138. # To allow reloading to potentially work, use a non-hacked loader which
  139. # won't rely on a now-closed file object.
  140. module.__loader__ = SourcelessFileLoader(name, pathname)
  141. module.__spec__.loader = module.__loader__
  142. return module
  143. def load_package(name, path):
  144. """**DEPRECATED**"""
  145. if os.path.isdir(path):
  146. extensions = (machinery.SOURCE_SUFFIXES[:] +
  147. machinery.BYTECODE_SUFFIXES[:])
  148. for extension in extensions:
  149. init_path = os.path.join(path, '__init__' + extension)
  150. if os.path.exists(init_path):
  151. path = init_path
  152. break
  153. else:
  154. raise ValueError('{!r} is not a package'.format(path))
  155. spec = util.spec_from_file_location(name, path,
  156. submodule_search_locations=[])
  157. if name in sys.modules:
  158. return _exec(spec, sys.modules[name])
  159. else:
  160. return _load(spec)
  161. def load_module(name, file, filename, details):
  162. """**DEPRECATED**
  163. Load a module, given information returned by find_module().
  164. The module name must include the full package name, if any.
  165. """
  166. suffix, mode, type_ = details
  167. if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
  168. raise ValueError('invalid file open mode {!r}'.format(mode))
  169. elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
  170. msg = 'file object required for import (type code {})'.format(type_)
  171. raise ValueError(msg)
  172. elif type_ == PY_SOURCE:
  173. return load_source(name, filename, file)
  174. elif type_ == PY_COMPILED:
  175. return load_compiled(name, filename, file)
  176. elif type_ == C_EXTENSION and load_dynamic is not None:
  177. if file is None:
  178. with open(filename, 'rb') as opened_file:
  179. return load_dynamic(name, filename, opened_file)
  180. else:
  181. return load_dynamic(name, filename, file)
  182. elif type_ == PKG_DIRECTORY:
  183. return load_package(name, filename)
  184. elif type_ == C_BUILTIN:
  185. return init_builtin(name)
  186. elif type_ == PY_FROZEN:
  187. return init_frozen(name)
  188. else:
  189. msg = "Don't know how to import {} (type code {})".format(name, type_)
  190. raise ImportError(msg, name=name)
  191. def find_module(name, path=None):
  192. """**DEPRECATED**
  193. Search for a module.
  194. If path is omitted or None, search for a built-in, frozen or special
  195. module and continue search in sys.path. The module name cannot
  196. contain '.'; to search for a submodule of a package, pass the
  197. submodule name and the package's __path__.
  198. """
  199. if not isinstance(name, str):
  200. raise TypeError("'name' must be a str, not {}".format(type(name)))
  201. elif not isinstance(path, (type(None), list)):
  202. # Backwards-compatibility
  203. raise RuntimeError("'path' must be None or a list, "
  204. "not {}".format(type(path)))
  205. if path is None:
  206. if is_builtin(name):
  207. return None, None, ('', '', C_BUILTIN)
  208. elif is_frozen(name):
  209. return None, None, ('', '', PY_FROZEN)
  210. else:
  211. path = sys.path
  212. for entry in path:
  213. package_directory = os.path.join(entry, name)
  214. for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
  215. package_file_name = '__init__' + suffix
  216. file_path = os.path.join(package_directory, package_file_name)
  217. if os.path.isfile(file_path):
  218. return None, package_directory, ('', '', PKG_DIRECTORY)
  219. for suffix, mode, type_ in get_suffixes():
  220. file_name = name + suffix
  221. file_path = os.path.join(entry, file_name)
  222. if os.path.isfile(file_path):
  223. break
  224. else:
  225. continue
  226. break # Break out of outer loop when breaking out of inner loop.
  227. else:
  228. raise ImportError(_ERR_MSG.format(name), name=name)
  229. encoding = None
  230. if 'b' not in mode:
  231. with open(file_path, 'rb') as file:
  232. encoding = tokenize.detect_encoding(file.readline)[0]
  233. file = open(file_path, mode, encoding=encoding)
  234. return file, file_path, (suffix, mode, type_)
  235. def reload(module):
  236. """**DEPRECATED**
  237. Reload the module and return it.
  238. The module must have been successfully imported before.
  239. """
  240. return importlib.reload(module)
  241. def init_builtin(name):
  242. """**DEPRECATED**
  243. Load and return a built-in module by name, or None is such module doesn't
  244. exist
  245. """
  246. try:
  247. return _builtin_from_name(name)
  248. except ImportError:
  249. return None
  250. if create_dynamic:
  251. def load_dynamic(name, path, file=None):
  252. """**DEPRECATED**
  253. Load an extension module.
  254. """
  255. import importlib.machinery
  256. loader = importlib.machinery.ExtensionFileLoader(name, path)
  257. # Issue #24748: Skip the sys.modules check in _load_module_shim;
  258. # always load new extension
  259. spec = importlib.machinery.ModuleSpec(
  260. name=name, loader=loader, origin=path)
  261. return _load(spec)
  262. else:
  263. load_dynamic = None
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...