_bootstrap_external.py 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742
  1. """Core implementation of path-based import.
  2. This module is NOT meant to be directly imported! It has been designed such
  3. that it can be bootstrapped into Python as the implementation of import. As
  4. such it requires the injection of specific modules and attributes in order to
  5. work. One should use importlib as the public-facing version of this module.
  6. """
  7. # IMPORTANT: Whenever making changes to this module, be sure to run a top-level
  8. # `make regen-importlib` followed by `make` in order to get the frozen version
  9. # of the module updated. Not doing so will result in the Makefile to fail for
  10. # all others who don't have a ./python around to freeze the module in the early
  11. # stages of compilation.
  12. #
  13. # See importlib._setup() for what is injected into the global namespace.
  14. # When editing this code be aware that code executed at import time CANNOT
  15. # reference any injected objects! This includes not only global code but also
  16. # anything specified at the class level.
  17. # Module injected manually by _set_bootstrap_module()
  18. _bootstrap = None
  19. # Import builtin modules
  20. import _imp
  21. import _io
  22. import sys
  23. import _warnings
  24. import marshal
  25. _MS_WINDOWS = (sys.platform == 'win32')
  26. if _MS_WINDOWS:
  27. import nt as _os
  28. import winreg
  29. else:
  30. import posix as _os
  31. if _MS_WINDOWS:
  32. path_separators = ['\\', '/']
  33. else:
  34. path_separators = ['/']
  35. # Assumption made in _path_join()
  36. assert all(len(sep) == 1 for sep in path_separators)
  37. path_sep = path_separators[0]
  38. path_sep_tuple = tuple(path_separators)
  39. path_separators = ''.join(path_separators)
  40. _pathseps_with_colon = {f':{s}' for s in path_separators}
  41. # Bootstrap-related code ######################################################
  42. _CASE_INSENSITIVE_PLATFORMS_STR_KEY = 'win',
  43. _CASE_INSENSITIVE_PLATFORMS_BYTES_KEY = 'cygwin', 'darwin'
  44. _CASE_INSENSITIVE_PLATFORMS = (_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY
  45. + _CASE_INSENSITIVE_PLATFORMS_STR_KEY)
  46. def _make_relax_case():
  47. if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
  48. if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS_STR_KEY):
  49. key = 'PYTHONCASEOK'
  50. else:
  51. key = b'PYTHONCASEOK'
  52. def _relax_case():
  53. """True if filenames must be checked case-insensitively and ignore environment flags are not set."""
  54. return not sys.flags.ignore_environment and key in _os.environ
  55. else:
  56. def _relax_case():
  57. """True if filenames must be checked case-insensitively."""
  58. return False
  59. return _relax_case
  60. _relax_case = _make_relax_case()
  61. def _pack_uint32(x):
  62. """Convert a 32-bit integer to little-endian."""
  63. return (int(x) & 0xFFFFFFFF).to_bytes(4, 'little')
  64. def _unpack_uint32(data):
  65. """Convert 4 bytes in little-endian to an integer."""
  66. assert len(data) == 4
  67. return int.from_bytes(data, 'little')
  68. def _unpack_uint16(data):
  69. """Convert 2 bytes in little-endian to an integer."""
  70. assert len(data) == 2
  71. return int.from_bytes(data, 'little')
  72. if _MS_WINDOWS:
  73. def _path_join(*path_parts):
  74. """Replacement for os.path.join()."""
  75. if not path_parts:
  76. return ""
  77. if len(path_parts) == 1:
  78. return path_parts[0]
  79. root = ""
  80. path = []
  81. for new_root, tail in map(_os._path_splitroot, path_parts):
  82. if new_root.startswith(path_sep_tuple) or new_root.endswith(path_sep_tuple):
  83. root = new_root.rstrip(path_separators) or root
  84. path = [path_sep + tail]
  85. elif new_root.endswith(':'):
  86. if root.casefold() != new_root.casefold():
  87. # Drive relative paths have to be resolved by the OS, so we reset the
  88. # tail but do not add a path_sep prefix.
  89. root = new_root
  90. path = [tail]
  91. else:
  92. path.append(tail)
  93. else:
  94. root = new_root or root
  95. path.append(tail)
  96. path = [p.rstrip(path_separators) for p in path if p]
  97. if len(path) == 1 and not path[0]:
  98. # Avoid losing the root's trailing separator when joining with nothing
  99. return root + path_sep
  100. return root + path_sep.join(path)
  101. else:
  102. def _path_join(*path_parts):
  103. """Replacement for os.path.join()."""
  104. return path_sep.join([part.rstrip(path_separators)
  105. for part in path_parts if part])
  106. def _path_split(path):
  107. """Replacement for os.path.split()."""
  108. i = max(path.rfind(p) for p in path_separators)
  109. if i < 0:
  110. return '', path
  111. return path[:i], path[i + 1:]
  112. def _path_stat(path):
  113. """Stat the path.
  114. Made a separate function to make it easier to override in experiments
  115. (e.g. cache stat results).
  116. """
  117. return _os.stat(path)
  118. def _path_is_mode_type(path, mode):
  119. """Test whether the path is the specified mode type."""
  120. try:
  121. stat_info = _path_stat(path)
  122. except OSError:
  123. return False
  124. return (stat_info.st_mode & 0o170000) == mode
  125. def _path_isfile(path):
  126. """Replacement for os.path.isfile."""
  127. return _path_is_mode_type(path, 0o100000)
  128. def _path_isdir(path):
  129. """Replacement for os.path.isdir."""
  130. if not path:
  131. path = _os.getcwd()
  132. return _path_is_mode_type(path, 0o040000)
  133. if _MS_WINDOWS:
  134. def _path_isabs(path):
  135. """Replacement for os.path.isabs."""
  136. if not path:
  137. return False
  138. root = _os._path_splitroot(path)[0].replace('/', '\\')
  139. return len(root) > 1 and (root.startswith('\\\\') or root.endswith('\\'))
  140. else:
  141. def _path_isabs(path):
  142. """Replacement for os.path.isabs."""
  143. return path.startswith(path_separators)
  144. def _path_abspath(path):
  145. """Replacement for os.path.abspath."""
  146. if not _path_isabs(path):
  147. for sep in path_separators:
  148. path = path.removeprefix(f".{sep}")
  149. return _path_join(_os.getcwd(), path)
  150. else:
  151. return path
  152. def _write_atomic(path, data, mode=0o666):
  153. """Best-effort function to write data to a path atomically.
  154. Be prepared to handle a FileExistsError if concurrent writing of the
  155. temporary file is attempted."""
  156. # id() is used to generate a pseudo-random filename.
  157. path_tmp = f'{path}.{id(path)}'
  158. fd = _os.open(path_tmp,
  159. _os.O_EXCL | _os.O_CREAT | _os.O_WRONLY, mode & 0o666)
  160. try:
  161. # We first write data to a temporary file, and then use os.replace() to
  162. # perform an atomic rename.
  163. with _io.FileIO(fd, 'wb') as file:
  164. file.write(data)
  165. _os.replace(path_tmp, path)
  166. except OSError:
  167. try:
  168. _os.unlink(path_tmp)
  169. except OSError:
  170. pass
  171. raise
  172. _code_type = type(_write_atomic.__code__)
  173. # Finder/loader utility code ###############################################
  174. # Magic word to reject .pyc files generated by other Python versions.
  175. # It should change for each incompatible change to the bytecode.
  176. #
  177. # The value of CR and LF is incorporated so if you ever read or write
  178. # a .pyc file in text mode the magic number will be wrong; also, the
  179. # Apple MPW compiler swaps their values, botching string constants.
  180. #
  181. # There were a variety of old schemes for setting the magic number.
  182. # The current working scheme is to increment the previous value by
  183. # 10.
  184. #
  185. # Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
  186. # number also includes a new "magic tag", i.e. a human readable string used
  187. # to represent the magic number in __pycache__ directories. When you change
  188. # the magic number, you must also set a new unique magic tag. Generally this
  189. # can be named after the Python major version of the magic number bump, but
  190. # it can really be anything, as long as it's different than anything else
  191. # that's come before. The tags are included in the following table, starting
  192. # with Python 3.2a0.
  193. #
  194. # Known values:
  195. # Python 1.5: 20121
  196. # Python 1.5.1: 20121
  197. # Python 1.5.2: 20121
  198. # Python 1.6: 50428
  199. # Python 2.0: 50823
  200. # Python 2.0.1: 50823
  201. # Python 2.1: 60202
  202. # Python 2.1.1: 60202
  203. # Python 2.1.2: 60202
  204. # Python 2.2: 60717
  205. # Python 2.3a0: 62011
  206. # Python 2.3a0: 62021
  207. # Python 2.3a0: 62011 (!)
  208. # Python 2.4a0: 62041
  209. # Python 2.4a3: 62051
  210. # Python 2.4b1: 62061
  211. # Python 2.5a0: 62071
  212. # Python 2.5a0: 62081 (ast-branch)
  213. # Python 2.5a0: 62091 (with)
  214. # Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
  215. # Python 2.5b3: 62101 (fix wrong code: for x, in ...)
  216. # Python 2.5b3: 62111 (fix wrong code: x += yield)
  217. # Python 2.5c1: 62121 (fix wrong lnotab with for loops and
  218. # storing constants that should have been removed)
  219. # Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
  220. # Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
  221. # Python 2.6a1: 62161 (WITH_CLEANUP optimization)
  222. # Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
  223. # Python 2.7a0: 62181 (optimize conditional branches:
  224. # introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
  225. # Python 2.7a0 62191 (introduce SETUP_WITH)
  226. # Python 2.7a0 62201 (introduce BUILD_SET)
  227. # Python 2.7a0 62211 (introduce MAP_ADD and SET_ADD)
  228. # Python 3000: 3000
  229. # 3010 (removed UNARY_CONVERT)
  230. # 3020 (added BUILD_SET)
  231. # 3030 (added keyword-only parameters)
  232. # 3040 (added signature annotations)
  233. # 3050 (print becomes a function)
  234. # 3060 (PEP 3115 metaclass syntax)
  235. # 3061 (string literals become unicode)
  236. # 3071 (PEP 3109 raise changes)
  237. # 3081 (PEP 3137 make __file__ and __name__ unicode)
  238. # 3091 (kill str8 interning)
  239. # 3101 (merge from 2.6a0, see 62151)
  240. # 3103 (__file__ points to source file)
  241. # Python 3.0a4: 3111 (WITH_CLEANUP optimization).
  242. # Python 3.0b1: 3131 (lexical exception stacking, including POP_EXCEPT
  243. #3021)
  244. # Python 3.1a1: 3141 (optimize list, set and dict comprehensions:
  245. # change LIST_APPEND and SET_ADD, add MAP_ADD #2183)
  246. # Python 3.1a1: 3151 (optimize conditional branches:
  247. # introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE
  248. #4715)
  249. # Python 3.2a1: 3160 (add SETUP_WITH #6101)
  250. # tag: cpython-32
  251. # Python 3.2a2: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR #9225)
  252. # tag: cpython-32
  253. # Python 3.2a3 3180 (add DELETE_DEREF #4617)
  254. # Python 3.3a1 3190 (__class__ super closure changed)
  255. # Python 3.3a1 3200 (PEP 3155 __qualname__ added #13448)
  256. # Python 3.3a1 3210 (added size modulo 2**32 to the pyc header #13645)
  257. # Python 3.3a2 3220 (changed PEP 380 implementation #14230)
  258. # Python 3.3a4 3230 (revert changes to implicit __class__ closure #14857)
  259. # Python 3.4a1 3250 (evaluate positional default arguments before
  260. # keyword-only defaults #16967)
  261. # Python 3.4a1 3260 (add LOAD_CLASSDEREF; allow locals of class to override
  262. # free vars #17853)
  263. # Python 3.4a1 3270 (various tweaks to the __class__ closure #12370)
  264. # Python 3.4a1 3280 (remove implicit class argument)
  265. # Python 3.4a4 3290 (changes to __qualname__ computation #19301)
  266. # Python 3.4a4 3300 (more changes to __qualname__ computation #19301)
  267. # Python 3.4rc2 3310 (alter __qualname__ computation #20625)
  268. # Python 3.5a1 3320 (PEP 465: Matrix multiplication operator #21176)
  269. # Python 3.5b1 3330 (PEP 448: Additional Unpacking Generalizations #2292)
  270. # Python 3.5b2 3340 (fix dictionary display evaluation order #11205)
  271. # Python 3.5b3 3350 (add GET_YIELD_FROM_ITER opcode #24400)
  272. # Python 3.5.2 3351 (fix BUILD_MAP_UNPACK_WITH_CALL opcode #27286)
  273. # Python 3.6a0 3360 (add FORMAT_VALUE opcode #25483)
  274. # Python 3.6a1 3361 (lineno delta of code.co_lnotab becomes signed #26107)
  275. # Python 3.6a2 3370 (16 bit wordcode #26647)
  276. # Python 3.6a2 3371 (add BUILD_CONST_KEY_MAP opcode #27140)
  277. # Python 3.6a2 3372 (MAKE_FUNCTION simplification, remove MAKE_CLOSURE
  278. # #27095)
  279. # Python 3.6b1 3373 (add BUILD_STRING opcode #27078)
  280. # Python 3.6b1 3375 (add SETUP_ANNOTATIONS and STORE_ANNOTATION opcodes
  281. # #27985)
  282. # Python 3.6b1 3376 (simplify CALL_FUNCTIONs & BUILD_MAP_UNPACK_WITH_CALL
  283. #27213)
  284. # Python 3.6b1 3377 (set __class__ cell from type.__new__ #23722)
  285. # Python 3.6b2 3378 (add BUILD_TUPLE_UNPACK_WITH_CALL #28257)
  286. # Python 3.6rc1 3379 (more thorough __class__ validation #23722)
  287. # Python 3.7a1 3390 (add LOAD_METHOD and CALL_METHOD opcodes #26110)
  288. # Python 3.7a2 3391 (update GET_AITER #31709)
  289. # Python 3.7a4 3392 (PEP 552: Deterministic pycs #31650)
  290. # Python 3.7b1 3393 (remove STORE_ANNOTATION opcode #32550)
  291. # Python 3.7b5 3394 (restored docstring as the first stmt in the body;
  292. # this might affected the first line number #32911)
  293. # Python 3.8a1 3400 (move frame block handling to compiler #17611)
  294. # Python 3.8a1 3401 (add END_ASYNC_FOR #33041)
  295. # Python 3.8a1 3410 (PEP570 Python Positional-Only Parameters #36540)
  296. # Python 3.8b2 3411 (Reverse evaluation order of key: value in dict
  297. # comprehensions #35224)
  298. # Python 3.8b2 3412 (Swap the position of positional args and positional
  299. # only args in ast.arguments #37593)
  300. # Python 3.8b4 3413 (Fix "break" and "continue" in "finally" #37830)
  301. # Python 3.9a0 3420 (add LOAD_ASSERTION_ERROR #34880)
  302. # Python 3.9a0 3421 (simplified bytecode for with blocks #32949)
  303. # Python 3.9a0 3422 (remove BEGIN_FINALLY, END_FINALLY, CALL_FINALLY, POP_FINALLY bytecodes #33387)
  304. # Python 3.9a2 3423 (add IS_OP, CONTAINS_OP and JUMP_IF_NOT_EXC_MATCH bytecodes #39156)
  305. # Python 3.9a2 3424 (simplify bytecodes for *value unpacking)
  306. # Python 3.9a2 3425 (simplify bytecodes for **value unpacking)
  307. # Python 3.10a1 3430 (Make 'annotations' future by default)
  308. # Python 3.10a1 3431 (New line number table format -- PEP 626)
  309. # Python 3.10a2 3432 (Function annotation for MAKE_FUNCTION is changed from dict to tuple bpo-42202)
  310. # Python 3.10a2 3433 (RERAISE restores f_lasti if oparg != 0)
  311. # Python 3.10a6 3434 (PEP 634: Structural Pattern Matching)
  312. # Python 3.10a7 3435 Use instruction offsets (as opposed to byte offsets).
  313. # Python 3.10b1 3436 (Add GEN_START bytecode #43683)
  314. # Python 3.10b1 3437 (Undo making 'annotations' future by default - We like to dance among core devs!)
  315. # Python 3.10b1 3438 Safer line number table handling.
  316. # Python 3.10b1 3439 (Add ROT_N)
  317. # Python 3.11a1 3450 Use exception table for unwinding ("zero cost" exception handling)
  318. # Python 3.11a1 3451 (Add CALL_METHOD_KW)
  319. # Python 3.11a1 3452 (drop nlocals from marshaled code objects)
  320. # Python 3.11a1 3453 (add co_fastlocalnames and co_fastlocalkinds)
  321. # Python 3.11a1 3454 (compute cell offsets relative to locals bpo-43693)
  322. # Python 3.11a1 3455 (add MAKE_CELL bpo-43693)
  323. # Python 3.11a1 3456 (interleave cell args bpo-43693)
  324. # Python 3.11a1 3457 (Change localsplus to a bytes object bpo-43693)
  325. # Python 3.11a1 3458 (imported objects now don't use LOAD_METHOD/CALL_METHOD)
  326. # Python 3.11a1 3459 (PEP 657: add end line numbers and column offsets for instructions)
  327. # Python 3.11a1 3460 (Add co_qualname field to PyCodeObject bpo-44530)
  328. # Python 3.11a1 3461 (JUMP_ABSOLUTE must jump backwards)
  329. # Python 3.11a2 3462 (bpo-44511: remove COPY_DICT_WITHOUT_KEYS, change
  330. # MATCH_CLASS and MATCH_KEYS, and add COPY)
  331. # Python 3.11a3 3463 (bpo-45711: JUMP_IF_NOT_EXC_MATCH no longer pops the
  332. # active exception)
  333. # Python 3.11a3 3464 (bpo-45636: Merge numeric BINARY_*/INPLACE_* into
  334. # BINARY_OP)
  335. # Python 3.11a3 3465 (Add COPY_FREE_VARS opcode)
  336. # Python 3.11a4 3466 (bpo-45292: PEP-654 except*)
  337. # Python 3.11a4 3467 (Change CALL_xxx opcodes)
  338. # Python 3.11a4 3468 (Add SEND opcode)
  339. # Python 3.11a4 3469 (bpo-45711: remove type, traceback from exc_info)
  340. # Python 3.11a4 3470 (bpo-46221: PREP_RERAISE_STAR no longer pushes lasti)
  341. # Python 3.11a4 3471 (bpo-46202: remove pop POP_EXCEPT_AND_RERAISE)
  342. # Python 3.11a4 3472 (bpo-46009: replace GEN_START with POP_TOP)
  343. # Python 3.11a4 3473 (Add POP_JUMP_IF_NOT_NONE/POP_JUMP_IF_NONE opcodes)
  344. # Python 3.11a4 3474 (Add RESUME opcode)
  345. # Python 3.11a5 3475 (Add RETURN_GENERATOR opcode)
  346. # Python 3.11a5 3476 (Add ASYNC_GEN_WRAP opcode)
  347. # Python 3.11a5 3477 (Replace DUP_TOP/DUP_TOP_TWO with COPY and
  348. # ROT_TWO/ROT_THREE/ROT_FOUR/ROT_N with SWAP)
  349. # Python 3.11a5 3478 (New CALL opcodes)
  350. # Python 3.11a5 3479 (Add PUSH_NULL opcode)
  351. # Python 3.11a5 3480 (New CALL opcodes, second iteration)
  352. # Python 3.11a5 3481 (Use inline cache for BINARY_OP)
  353. # Python 3.11a5 3482 (Use inline caching for UNPACK_SEQUENCE and LOAD_GLOBAL)
  354. # Python 3.11a5 3483 (Use inline caching for COMPARE_OP and BINARY_SUBSCR)
  355. # Python 3.11a5 3484 (Use inline caching for LOAD_ATTR, LOAD_METHOD, and
  356. # STORE_ATTR)
  357. # Python 3.11a5 3485 (Add an oparg to GET_AWAITABLE)
  358. # Python 3.11a6 3486 (Use inline caching for PRECALL and CALL)
  359. # Python 3.11a6 3487 (Remove the adaptive "oparg counter" mechanism)
  360. # Python 3.11a6 3488 (LOAD_GLOBAL can push additional NULL)
  361. # Python 3.11a6 3489 (Add JUMP_BACKWARD, remove JUMP_ABSOLUTE)
  362. # Python 3.11a6 3490 (remove JUMP_IF_NOT_EXC_MATCH, add CHECK_EXC_MATCH)
  363. # Python 3.11a6 3491 (remove JUMP_IF_NOT_EG_MATCH, add CHECK_EG_MATCH,
  364. # add JUMP_BACKWARD_NO_INTERRUPT, make JUMP_NO_INTERRUPT virtual)
  365. # Python 3.11a7 3492 (make POP_JUMP_IF_NONE/NOT_NONE/TRUE/FALSE relative)
  366. # Python 3.11a7 3493 (Make JUMP_IF_TRUE_OR_POP/JUMP_IF_FALSE_OR_POP relative)
  367. # Python 3.11a7 3494 (New location info table)
  368. # Python 3.11b4 3495 (Set line number of module's RESUME instr to 0 per PEP 626)
  369. # Python 3.12a1 3500 (Remove PRECALL opcode)
  370. # Python 3.12a1 3501 (YIELD_VALUE oparg == stack_depth)
  371. # Python 3.12a1 3502 (LOAD_FAST_CHECK, no NULL-check in LOAD_FAST)
  372. # Python 3.12a1 3503 (Shrink LOAD_METHOD cache)
  373. # Python 3.12a1 3504 (Merge LOAD_METHOD back into LOAD_ATTR)
  374. # Python 3.12a1 3505 (Specialization/Cache for FOR_ITER)
  375. # Python 3.12a1 3506 (Add BINARY_SLICE and STORE_SLICE instructions)
  376. # Python 3.12a1 3507 (Set lineno of module's RESUME to 0)
  377. # Python 3.12a1 3508 (Add CLEANUP_THROW)
  378. # Python 3.12a1 3509 (Conditional jumps only jump forward)
  379. # Python 3.12a2 3510 (FOR_ITER leaves iterator on the stack)
  380. # Python 3.12a2 3511 (Add STOPITERATION_ERROR instruction)
  381. # Python 3.12a2 3512 (Remove all unused consts from code objects)
  382. # Python 3.12a4 3513 (Add CALL_INTRINSIC_1 instruction, removed STOPITERATION_ERROR, PRINT_EXPR, IMPORT_STAR)
  383. # Python 3.12a4 3514 (Remove ASYNC_GEN_WRAP, LIST_TO_TUPLE, and UNARY_POSITIVE)
  384. # Python 3.12a5 3515 (Embed jump mask in COMPARE_OP oparg)
  385. # Python 3.12a5 3516 (Add COMPARE_AND_BRANCH instruction)
  386. # Python 3.12a5 3517 (Change YIELD_VALUE oparg to exception block depth)
  387. # Python 3.12a6 3518 (Add RETURN_CONST instruction)
  388. # Python 3.12a6 3519 (Modify SEND instruction)
  389. # Python 3.12a6 3520 (Remove PREP_RERAISE_STAR, add CALL_INTRINSIC_2)
  390. # Python 3.12a7 3521 (Shrink the LOAD_GLOBAL caches)
  391. # Python 3.12a7 3522 (Removed JUMP_IF_FALSE_OR_POP/JUMP_IF_TRUE_OR_POP)
  392. # Python 3.12a7 3523 (Convert COMPARE_AND_BRANCH back to COMPARE_OP)
  393. # Python 3.12a7 3524 (Shrink the BINARY_SUBSCR caches)
  394. # Python 3.12b1 3525 (Shrink the CALL caches)
  395. # Python 3.12b1 3526 (Add instrumentation support)
  396. # Python 3.12b1 3527 (Add LOAD_SUPER_ATTR)
  397. # Python 3.12b1 3528 (Add LOAD_SUPER_ATTR_METHOD specialization)
  398. # Python 3.12b1 3529 (Inline list/dict/set comprehensions)
  399. # Python 3.12b1 3530 (Shrink the LOAD_SUPER_ATTR caches)
  400. # Python 3.12b1 3531 (Add PEP 695 changes)
  401. # Python 3.13 will start with 3550
  402. # Please don't copy-paste the same pre-release tag for new entries above!!!
  403. # You should always use the *upcoming* tag. For example, if 3.12a6 came out
  404. # a week ago, I should put "Python 3.12a7" next to my new magic number.
  405. # MAGIC must change whenever the bytecode emitted by the compiler may no
  406. # longer be understood by older implementations of the eval loop (usually
  407. # due to the addition of new opcodes).
  408. #
  409. # Starting with Python 3.11, Python 3.n starts with magic number 2900+50n.
  410. #
  411. # Whenever MAGIC_NUMBER is changed, the ranges in the magic_values array
  412. # in PC/launcher.c must also be updated.
  413. MAGIC_NUMBER = (3531).to_bytes(2, 'little') + b'\r\n'
  414. _RAW_MAGIC_NUMBER = int.from_bytes(MAGIC_NUMBER, 'little') # For import.c
  415. _PYCACHE = '__pycache__'
  416. _OPT = 'opt-'
  417. SOURCE_SUFFIXES = ['.py']
  418. if _MS_WINDOWS:
  419. SOURCE_SUFFIXES.append('.pyw')
  420. EXTENSION_SUFFIXES = _imp.extension_suffixes()
  421. BYTECODE_SUFFIXES = ['.pyc']
  422. # Deprecated.
  423. DEBUG_BYTECODE_SUFFIXES = OPTIMIZED_BYTECODE_SUFFIXES = BYTECODE_SUFFIXES
  424. def cache_from_source(path, debug_override=None, *, optimization=None):
  425. """Given the path to a .py file, return the path to its .pyc file.
  426. The .py file does not need to exist; this simply returns the path to the
  427. .pyc file calculated as if the .py file were imported.
  428. The 'optimization' parameter controls the presumed optimization level of
  429. the bytecode file. If 'optimization' is not None, the string representation
  430. of the argument is taken and verified to be alphanumeric (else ValueError
  431. is raised).
  432. The debug_override parameter is deprecated. If debug_override is not None,
  433. a True value is the same as setting 'optimization' to the empty string
  434. while a False value is equivalent to setting 'optimization' to '1'.
  435. If sys.implementation.cache_tag is None then NotImplementedError is raised.
  436. """
  437. if debug_override is not None:
  438. _warnings.warn('the debug_override parameter is deprecated; use '
  439. "'optimization' instead", DeprecationWarning)
  440. if optimization is not None:
  441. message = 'debug_override or optimization must be set to None'
  442. raise TypeError(message)
  443. optimization = '' if debug_override else 1
  444. path = _os.fspath(path)
  445. head, tail = _path_split(path)
  446. base, sep, rest = tail.rpartition('.')
  447. tag = sys.implementation.cache_tag
  448. if tag is None:
  449. raise NotImplementedError('sys.implementation.cache_tag is None')
  450. almost_filename = ''.join([(base if base else rest), sep, tag])
  451. if optimization is None:
  452. if sys.flags.optimize == 0:
  453. optimization = ''
  454. else:
  455. optimization = sys.flags.optimize
  456. optimization = str(optimization)
  457. if optimization != '':
  458. if not optimization.isalnum():
  459. raise ValueError(f'{optimization!r} is not alphanumeric')
  460. almost_filename = f'{almost_filename}.{_OPT}{optimization}'
  461. filename = almost_filename + BYTECODE_SUFFIXES[0]
  462. if sys.pycache_prefix is not None:
  463. # We need an absolute path to the py file to avoid the possibility of
  464. # collisions within sys.pycache_prefix, if someone has two different
  465. # `foo/bar.py` on their system and they import both of them using the
  466. # same sys.pycache_prefix. Let's say sys.pycache_prefix is
  467. # `C:\Bytecode`; the idea here is that if we get `Foo\Bar`, we first
  468. # make it absolute (`C:\Somewhere\Foo\Bar`), then make it root-relative
  469. # (`Somewhere\Foo\Bar`), so we end up placing the bytecode file in an
  470. # unambiguous `C:\Bytecode\Somewhere\Foo\Bar\`.
  471. head = _path_abspath(head)
  472. # Strip initial drive from a Windows path. We know we have an absolute
  473. # path here, so the second part of the check rules out a POSIX path that
  474. # happens to contain a colon at the second character.
  475. if head[1] == ':' and head[0] not in path_separators:
  476. head = head[2:]
  477. # Strip initial path separator from `head` to complete the conversion
  478. # back to a root-relative path before joining.
  479. return _path_join(
  480. sys.pycache_prefix,
  481. head.lstrip(path_separators),
  482. filename,
  483. )
  484. return _path_join(head, _PYCACHE, filename)
  485. def source_from_cache(path):
  486. """Given the path to a .pyc. file, return the path to its .py file.
  487. The .pyc file does not need to exist; this simply returns the path to
  488. the .py file calculated to correspond to the .pyc file. If path does
  489. not conform to PEP 3147/488 format, ValueError will be raised. If
  490. sys.implementation.cache_tag is None then NotImplementedError is raised.
  491. """
  492. if sys.implementation.cache_tag is None:
  493. raise NotImplementedError('sys.implementation.cache_tag is None')
  494. path = _os.fspath(path)
  495. head, pycache_filename = _path_split(path)
  496. found_in_pycache_prefix = False
  497. if sys.pycache_prefix is not None:
  498. stripped_path = sys.pycache_prefix.rstrip(path_separators)
  499. if head.startswith(stripped_path + path_sep):
  500. head = head[len(stripped_path):]
  501. found_in_pycache_prefix = True
  502. if not found_in_pycache_prefix:
  503. head, pycache = _path_split(head)
  504. if pycache != _PYCACHE:
  505. raise ValueError(f'{_PYCACHE} not bottom-level directory in '
  506. f'{path!r}')
  507. dot_count = pycache_filename.count('.')
  508. if dot_count not in {2, 3}:
  509. raise ValueError(f'expected only 2 or 3 dots in {pycache_filename!r}')
  510. elif dot_count == 3:
  511. optimization = pycache_filename.rsplit('.', 2)[-2]
  512. if not optimization.startswith(_OPT):
  513. raise ValueError("optimization portion of filename does not start "
  514. f"with {_OPT!r}")
  515. opt_level = optimization[len(_OPT):]
  516. if not opt_level.isalnum():
  517. raise ValueError(f"optimization level {optimization!r} is not an "
  518. "alphanumeric value")
  519. base_filename = pycache_filename.partition('.')[0]
  520. return _path_join(head, base_filename + SOURCE_SUFFIXES[0])
  521. def _get_sourcefile(bytecode_path):
  522. """Convert a bytecode file path to a source path (if possible).
  523. This function exists purely for backwards-compatibility for
  524. PyImport_ExecCodeModuleWithFilenames() in the C API.
  525. """
  526. if len(bytecode_path) == 0:
  527. return None
  528. rest, _, extension = bytecode_path.rpartition('.')
  529. if not rest or extension.lower()[-3:-1] != 'py':
  530. return bytecode_path
  531. try:
  532. source_path = source_from_cache(bytecode_path)
  533. except (NotImplementedError, ValueError):
  534. source_path = bytecode_path[:-1]
  535. return source_path if _path_isfile(source_path) else bytecode_path
  536. def _get_cached(filename):
  537. if filename.endswith(tuple(SOURCE_SUFFIXES)):
  538. try:
  539. return cache_from_source(filename)
  540. except NotImplementedError:
  541. pass
  542. elif filename.endswith(tuple(BYTECODE_SUFFIXES)):
  543. return filename
  544. else:
  545. return None
  546. def _calc_mode(path):
  547. """Calculate the mode permissions for a bytecode file."""
  548. try:
  549. mode = _path_stat(path).st_mode
  550. except OSError:
  551. mode = 0o666
  552. # We always ensure write access so we can update cached files
  553. # later even when the source files are read-only on Windows (#6074)
  554. mode |= 0o200
  555. return mode
  556. def _check_name(method):
  557. """Decorator to verify that the module being requested matches the one the
  558. loader can handle.
  559. The first argument (self) must define _name which the second argument is
  560. compared against. If the comparison fails then ImportError is raised.
  561. """
  562. def _check_name_wrapper(self, name=None, *args, **kwargs):
  563. if name is None:
  564. name = self.name
  565. elif self.name != name:
  566. raise ImportError('loader for %s cannot handle %s' %
  567. (self.name, name), name=name)
  568. return method(self, name, *args, **kwargs)
  569. # FIXME: @_check_name is used to define class methods before the
  570. # _bootstrap module is set by _set_bootstrap_module().
  571. if _bootstrap is not None:
  572. _wrap = _bootstrap._wrap
  573. else:
  574. def _wrap(new, old):
  575. for replace in ['__module__', '__name__', '__qualname__', '__doc__']:
  576. if hasattr(old, replace):
  577. setattr(new, replace, getattr(old, replace))
  578. new.__dict__.update(old.__dict__)
  579. _wrap(_check_name_wrapper, method)
  580. return _check_name_wrapper
  581. def _classify_pyc(data, name, exc_details):
  582. """Perform basic validity checking of a pyc header and return the flags field,
  583. which determines how the pyc should be further validated against the source.
  584. *data* is the contents of the pyc file. (Only the first 16 bytes are
  585. required, though.)
  586. *name* is the name of the module being imported. It is used for logging.
  587. *exc_details* is a dictionary passed to ImportError if it raised for
  588. improved debugging.
  589. ImportError is raised when the magic number is incorrect or when the flags
  590. field is invalid. EOFError is raised when the data is found to be truncated.
  591. """
  592. magic = data[:4]
  593. if magic != MAGIC_NUMBER:
  594. message = f'bad magic number in {name!r}: {magic!r}'
  595. _bootstrap._verbose_message('{}', message)
  596. raise ImportError(message, **exc_details)
  597. if len(data) < 16:
  598. message = f'reached EOF while reading pyc header of {name!r}'
  599. _bootstrap._verbose_message('{}', message)
  600. raise EOFError(message)
  601. flags = _unpack_uint32(data[4:8])
  602. # Only the first two flags are defined.
  603. if flags & ~0b11:
  604. message = f'invalid flags {flags!r} in {name!r}'
  605. raise ImportError(message, **exc_details)
  606. return flags
  607. def _validate_timestamp_pyc(data, source_mtime, source_size, name,
  608. exc_details):
  609. """Validate a pyc against the source last-modified time.
  610. *data* is the contents of the pyc file. (Only the first 16 bytes are
  611. required.)
  612. *source_mtime* is the last modified timestamp of the source file.
  613. *source_size* is None or the size of the source file in bytes.
  614. *name* is the name of the module being imported. It is used for logging.
  615. *exc_details* is a dictionary passed to ImportError if it raised for
  616. improved debugging.
  617. An ImportError is raised if the bytecode is stale.
  618. """
  619. if _unpack_uint32(data[8:12]) != (source_mtime & 0xFFFFFFFF):
  620. message = f'bytecode is stale for {name!r}'
  621. _bootstrap._verbose_message('{}', message)
  622. raise ImportError(message, **exc_details)
  623. if (source_size is not None and
  624. _unpack_uint32(data[12:16]) != (source_size & 0xFFFFFFFF)):
  625. raise ImportError(f'bytecode is stale for {name!r}', **exc_details)
  626. def _validate_hash_pyc(data, source_hash, name, exc_details):
  627. """Validate a hash-based pyc by checking the real source hash against the one in
  628. the pyc header.
  629. *data* is the contents of the pyc file. (Only the first 16 bytes are
  630. required.)
  631. *source_hash* is the importlib.util.source_hash() of the source file.
  632. *name* is the name of the module being imported. It is used for logging.
  633. *exc_details* is a dictionary passed to ImportError if it raised for
  634. improved debugging.
  635. An ImportError is raised if the bytecode is stale.
  636. """
  637. if data[8:16] != source_hash:
  638. raise ImportError(
  639. f'hash in bytecode doesn\'t match hash of source {name!r}',
  640. **exc_details,
  641. )
  642. def _compile_bytecode(data, name=None, bytecode_path=None, source_path=None):
  643. """Compile bytecode as found in a pyc."""
  644. code = marshal.loads(data)
  645. if isinstance(code, _code_type):
  646. _bootstrap._verbose_message('code object from {!r}', bytecode_path)
  647. if source_path is not None:
  648. _imp._fix_co_filename(code, source_path)
  649. return code
  650. else:
  651. raise ImportError(f'Non-code object in {bytecode_path!r}',
  652. name=name, path=bytecode_path)
  653. def _code_to_timestamp_pyc(code, mtime=0, source_size=0):
  654. "Produce the data for a timestamp-based pyc."
  655. data = bytearray(MAGIC_NUMBER)
  656. data.extend(_pack_uint32(0))
  657. data.extend(_pack_uint32(mtime))
  658. data.extend(_pack_uint32(source_size))
  659. data.extend(marshal.dumps(code))
  660. return data
  661. def _code_to_hash_pyc(code, source_hash, checked=True):
  662. "Produce the data for a hash-based pyc."
  663. data = bytearray(MAGIC_NUMBER)
  664. flags = 0b1 | checked << 1
  665. data.extend(_pack_uint32(flags))
  666. assert len(source_hash) == 8
  667. data.extend(source_hash)
  668. data.extend(marshal.dumps(code))
  669. return data
  670. def decode_source(source_bytes):
  671. """Decode bytes representing source code and return the string.
  672. Universal newline support is used in the decoding.
  673. """
  674. import tokenize # To avoid bootstrap issues.
  675. source_bytes_readline = _io.BytesIO(source_bytes).readline
  676. encoding = tokenize.detect_encoding(source_bytes_readline)
  677. newline_decoder = _io.IncrementalNewlineDecoder(None, True)
  678. return newline_decoder.decode(source_bytes.decode(encoding[0]))
  679. # Module specifications #######################################################
  680. _POPULATE = object()
  681. def spec_from_file_location(name, location=None, *, loader=None,
  682. submodule_search_locations=_POPULATE):
  683. """Return a module spec based on a file location.
  684. To indicate that the module is a package, set
  685. submodule_search_locations to a list of directory paths. An
  686. empty list is sufficient, though its not otherwise useful to the
  687. import system.
  688. The loader must take a spec as its only __init__() arg.
  689. """
  690. if location is None:
  691. # The caller may simply want a partially populated location-
  692. # oriented spec. So we set the location to a bogus value and
  693. # fill in as much as we can.
  694. location = '<unknown>'
  695. if hasattr(loader, 'get_filename'):
  696. # ExecutionLoader
  697. try:
  698. location = loader.get_filename(name)
  699. except ImportError:
  700. pass
  701. else:
  702. location = _os.fspath(location)
  703. try:
  704. location = _path_abspath(location)
  705. except OSError:
  706. pass
  707. # If the location is on the filesystem, but doesn't actually exist,
  708. # we could return None here, indicating that the location is not
  709. # valid. However, we don't have a good way of testing since an
  710. # indirect location (e.g. a zip file or URL) will look like a
  711. # non-existent file relative to the filesystem.
  712. spec = _bootstrap.ModuleSpec(name, loader, origin=location)
  713. spec._set_fileattr = True
  714. # Pick a loader if one wasn't provided.
  715. if loader is None:
  716. for loader_class, suffixes in _get_supported_file_loaders():
  717. if location.endswith(tuple(suffixes)):
  718. loader = loader_class(name, location)
  719. spec.loader = loader
  720. break
  721. else:
  722. return None
  723. # Set submodule_search_paths appropriately.
  724. if submodule_search_locations is _POPULATE:
  725. # Check the loader.
  726. if hasattr(loader, 'is_package'):
  727. try:
  728. is_package = loader.is_package(name)
  729. except ImportError:
  730. pass
  731. else:
  732. if is_package:
  733. spec.submodule_search_locations = []
  734. else:
  735. spec.submodule_search_locations = submodule_search_locations
  736. if spec.submodule_search_locations == []:
  737. if location:
  738. dirname = _path_split(location)[0]
  739. spec.submodule_search_locations.append(dirname)
  740. return spec
  741. def _bless_my_loader(module_globals):
  742. """Helper function for _warnings.c
  743. See GH#97850 for details.
  744. """
  745. # 2022-10-06(warsaw): For now, this helper is only used in _warnings.c and
  746. # that use case only has the module globals. This function could be
  747. # extended to accept either that or a module object. However, in the
  748. # latter case, it would be better to raise certain exceptions when looking
  749. # at a module, which should have either a __loader__ or __spec__.loader.
  750. # For backward compatibility, it is possible that we'll get an empty
  751. # dictionary for the module globals, and that cannot raise an exception.
  752. if not isinstance(module_globals, dict):
  753. return None
  754. missing = object()
  755. loader = module_globals.get('__loader__', None)
  756. spec = module_globals.get('__spec__', missing)
  757. if loader is None:
  758. if spec is missing:
  759. # If working with a module:
  760. # raise AttributeError('Module globals is missing a __spec__')
  761. return None
  762. elif spec is None:
  763. raise ValueError('Module globals is missing a __spec__.loader')
  764. spec_loader = getattr(spec, 'loader', missing)
  765. if spec_loader in (missing, None):
  766. if loader is None:
  767. exc = AttributeError if spec_loader is missing else ValueError
  768. raise exc('Module globals is missing a __spec__.loader')
  769. _warnings.warn(
  770. 'Module globals is missing a __spec__.loader',
  771. DeprecationWarning)
  772. spec_loader = loader
  773. assert spec_loader is not None
  774. if loader is not None and loader != spec_loader:
  775. _warnings.warn(
  776. 'Module globals; __loader__ != __spec__.loader',
  777. DeprecationWarning)
  778. return loader
  779. return spec_loader
  780. # Loaders #####################################################################
  781. class WindowsRegistryFinder:
  782. """Meta path finder for modules declared in the Windows registry."""
  783. REGISTRY_KEY = (
  784. 'Software\\Python\\PythonCore\\{sys_version}'
  785. '\\Modules\\{fullname}')
  786. REGISTRY_KEY_DEBUG = (
  787. 'Software\\Python\\PythonCore\\{sys_version}'
  788. '\\Modules\\{fullname}\\Debug')
  789. DEBUG_BUILD = (_MS_WINDOWS and '_d.pyd' in EXTENSION_SUFFIXES)
  790. @staticmethod
  791. def _open_registry(key):
  792. try:
  793. return winreg.OpenKey(winreg.HKEY_CURRENT_USER, key)
  794. except OSError:
  795. return winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key)
  796. @classmethod
  797. def _search_registry(cls, fullname):
  798. if cls.DEBUG_BUILD:
  799. registry_key = cls.REGISTRY_KEY_DEBUG
  800. else:
  801. registry_key = cls.REGISTRY_KEY
  802. key = registry_key.format(fullname=fullname,
  803. sys_version='%d.%d' % sys.version_info[:2])
  804. try:
  805. with cls._open_registry(key) as hkey:
  806. filepath = winreg.QueryValue(hkey, '')
  807. except OSError:
  808. return None
  809. return filepath
  810. @classmethod
  811. def find_spec(cls, fullname, path=None, target=None):
  812. filepath = cls._search_registry(fullname)
  813. if filepath is None:
  814. return None
  815. try:
  816. _path_stat(filepath)
  817. except OSError:
  818. return None
  819. for loader, suffixes in _get_supported_file_loaders():
  820. if filepath.endswith(tuple(suffixes)):
  821. spec = _bootstrap.spec_from_loader(fullname,
  822. loader(fullname, filepath),
  823. origin=filepath)
  824. return spec
  825. class _LoaderBasics:
  826. """Base class of common code needed by both SourceLoader and
  827. SourcelessFileLoader."""
  828. def is_package(self, fullname):
  829. """Concrete implementation of InspectLoader.is_package by checking if
  830. the path returned by get_filename has a filename of '__init__.py'."""
  831. filename = _path_split(self.get_filename(fullname))[1]
  832. filename_base = filename.rsplit('.', 1)[0]
  833. tail_name = fullname.rpartition('.')[2]
  834. return filename_base == '__init__' and tail_name != '__init__'
  835. def create_module(self, spec):
  836. """Use default semantics for module creation."""
  837. def exec_module(self, module):
  838. """Execute the module."""
  839. code = self.get_code(module.__name__)
  840. if code is None:
  841. raise ImportError(f'cannot load module {module.__name__!r} when '
  842. 'get_code() returns None')
  843. _bootstrap._call_with_frames_removed(exec, code, module.__dict__)
  844. def load_module(self, fullname):
  845. """This method is deprecated."""
  846. # Warning implemented in _load_module_shim().
  847. return _bootstrap._load_module_shim(self, fullname)
  848. class SourceLoader(_LoaderBasics):
  849. def path_mtime(self, path):
  850. """Optional method that returns the modification time (an int) for the
  851. specified path (a str).
  852. Raises OSError when the path cannot be handled.
  853. """
  854. raise OSError
  855. def path_stats(self, path):
  856. """Optional method returning a metadata dict for the specified
  857. path (a str).
  858. Possible keys:
  859. - 'mtime' (mandatory) is the numeric timestamp of last source
  860. code modification;
  861. - 'size' (optional) is the size in bytes of the source code.
  862. Implementing this method allows the loader to read bytecode files.
  863. Raises OSError when the path cannot be handled.
  864. """
  865. return {'mtime': self.path_mtime(path)}
  866. def _cache_bytecode(self, source_path, cache_path, data):
  867. """Optional method which writes data (bytes) to a file path (a str).
  868. Implementing this method allows for the writing of bytecode files.
  869. The source path is needed in order to correctly transfer permissions
  870. """
  871. # For backwards compatibility, we delegate to set_data()
  872. return self.set_data(cache_path, data)
  873. def set_data(self, path, data):
  874. """Optional method which writes data (bytes) to a file path (a str).
  875. Implementing this method allows for the writing of bytecode files.
  876. """
  877. def get_source(self, fullname):
  878. """Concrete implementation of InspectLoader.get_source."""
  879. path = self.get_filename(fullname)
  880. try:
  881. source_bytes = self.get_data(path)
  882. except OSError as exc:
  883. raise ImportError('source not available through get_data()',
  884. name=fullname) from exc
  885. return decode_source(source_bytes)
  886. def source_to_code(self, data, path, *, _optimize=-1):
  887. """Return the code object compiled from source.
  888. The 'data' argument can be any object type that compile() supports.
  889. """
  890. return _bootstrap._call_with_frames_removed(compile, data, path, 'exec',
  891. dont_inherit=True, optimize=_optimize)
  892. def get_code(self, fullname):
  893. """Concrete implementation of InspectLoader.get_code.
  894. Reading of bytecode requires path_stats to be implemented. To write
  895. bytecode, set_data must also be implemented.
  896. """
  897. source_path = self.get_filename(fullname)
  898. source_mtime = None
  899. source_bytes = None
  900. source_hash = None
  901. hash_based = False
  902. check_source = True
  903. try:
  904. bytecode_path = cache_from_source(source_path)
  905. except NotImplementedError:
  906. bytecode_path = None
  907. else:
  908. try:
  909. st = self.path_stats(source_path)
  910. except OSError:
  911. pass
  912. else:
  913. source_mtime = int(st['mtime'])
  914. try:
  915. data = self.get_data(bytecode_path)
  916. except OSError:
  917. pass
  918. else:
  919. exc_details = {
  920. 'name': fullname,
  921. 'path': bytecode_path,
  922. }
  923. try:
  924. flags = _classify_pyc(data, fullname, exc_details)
  925. bytes_data = memoryview(data)[16:]
  926. hash_based = flags & 0b1 != 0
  927. if hash_based:
  928. check_source = flags & 0b10 != 0
  929. if (_imp.check_hash_based_pycs != 'never' and
  930. (check_source or
  931. _imp.check_hash_based_pycs == 'always')):
  932. source_bytes = self.get_data(source_path)
  933. source_hash = _imp.source_hash(
  934. _RAW_MAGIC_NUMBER,
  935. source_bytes,
  936. )
  937. _validate_hash_pyc(data, source_hash, fullname,
  938. exc_details)
  939. else:
  940. _validate_timestamp_pyc(
  941. data,
  942. source_mtime,
  943. st['size'],
  944. fullname,
  945. exc_details,
  946. )
  947. except (ImportError, EOFError):
  948. pass
  949. else:
  950. _bootstrap._verbose_message('{} matches {}', bytecode_path,
  951. source_path)
  952. return _compile_bytecode(bytes_data, name=fullname,
  953. bytecode_path=bytecode_path,
  954. source_path=source_path)
  955. if source_bytes is None:
  956. source_bytes = self.get_data(source_path)
  957. code_object = self.source_to_code(source_bytes, source_path)
  958. _bootstrap._verbose_message('code object from {}', source_path)
  959. if (not sys.dont_write_bytecode and bytecode_path is not None and
  960. source_mtime is not None):
  961. if hash_based:
  962. if source_hash is None:
  963. source_hash = _imp.source_hash(_RAW_MAGIC_NUMBER,
  964. source_bytes)
  965. data = _code_to_hash_pyc(code_object, source_hash, check_source)
  966. else:
  967. data = _code_to_timestamp_pyc(code_object, source_mtime,
  968. len(source_bytes))
  969. try:
  970. self._cache_bytecode(source_path, bytecode_path, data)
  971. except NotImplementedError:
  972. pass
  973. return code_object
  974. class FileLoader:
  975. """Base file loader class which implements the loader protocol methods that
  976. require file system usage."""
  977. def __init__(self, fullname, path):
  978. """Cache the module name and the path to the file found by the
  979. finder."""
  980. self.name = fullname
  981. self.path = path
  982. def __eq__(self, other):
  983. return (self.__class__ == other.__class__ and
  984. self.__dict__ == other.__dict__)
  985. def __hash__(self):
  986. return hash(self.name) ^ hash(self.path)
  987. @_check_name
  988. def load_module(self, fullname):
  989. """Load a module from a file.
  990. This method is deprecated. Use exec_module() instead.
  991. """
  992. # The only reason for this method is for the name check.
  993. # Issue #14857: Avoid the zero-argument form of super so the implementation
  994. # of that form can be updated without breaking the frozen module.
  995. return super(FileLoader, self).load_module(fullname)
  996. @_check_name
  997. def get_filename(self, fullname):
  998. """Return the path to the source file as found by the finder."""
  999. return self.path
  1000. def get_data(self, path):
  1001. """Return the data from path as raw bytes."""
  1002. if isinstance(self, (SourceLoader, ExtensionFileLoader)):
  1003. with _io.open_code(str(path)) as file:
  1004. return file.read()
  1005. else:
  1006. with _io.FileIO(path, 'r') as file:
  1007. return file.read()
  1008. @_check_name
  1009. def get_resource_reader(self, module):
  1010. from importlib.readers import FileReader
  1011. return FileReader(self)
  1012. class SourceFileLoader(FileLoader, SourceLoader):
  1013. """Concrete implementation of SourceLoader using the file system."""
  1014. def path_stats(self, path):
  1015. """Return the metadata for the path."""
  1016. st = _path_stat(path)
  1017. return {'mtime': st.st_mtime, 'size': st.st_size}
  1018. def _cache_bytecode(self, source_path, bytecode_path, data):
  1019. # Adapt between the two APIs
  1020. mode = _calc_mode(source_path)
  1021. return self.set_data(bytecode_path, data, _mode=mode)
  1022. def set_data(self, path, data, *, _mode=0o666):
  1023. """Write bytes data to a file."""
  1024. parent, filename = _path_split(path)
  1025. path_parts = []
  1026. # Figure out what directories are missing.
  1027. while parent and not _path_isdir(parent):
  1028. parent, part = _path_split(parent)
  1029. path_parts.append(part)
  1030. # Create needed directories.
  1031. for part in reversed(path_parts):
  1032. parent = _path_join(parent, part)
  1033. try:
  1034. _os.mkdir(parent)
  1035. except FileExistsError:
  1036. # Probably another Python process already created the dir.
  1037. continue
  1038. except OSError as exc:
  1039. # Could be a permission error, read-only filesystem: just forget
  1040. # about writing the data.
  1041. _bootstrap._verbose_message('could not create {!r}: {!r}',
  1042. parent, exc)
  1043. return
  1044. try:
  1045. _write_atomic(path, data, _mode)
  1046. _bootstrap._verbose_message('created {!r}', path)
  1047. except OSError as exc:
  1048. # Same as above: just don't write the bytecode.
  1049. _bootstrap._verbose_message('could not create {!r}: {!r}', path,
  1050. exc)
  1051. class SourcelessFileLoader(FileLoader, _LoaderBasics):
  1052. """Loader which handles sourceless file imports."""
  1053. def get_code(self, fullname):
  1054. path = self.get_filename(fullname)
  1055. data = self.get_data(path)
  1056. # Call _classify_pyc to do basic validation of the pyc but ignore the
  1057. # result. There's no source to check against.
  1058. exc_details = {
  1059. 'name': fullname,
  1060. 'path': path,
  1061. }
  1062. _classify_pyc(data, fullname, exc_details)
  1063. return _compile_bytecode(
  1064. memoryview(data)[16:],
  1065. name=fullname,
  1066. bytecode_path=path,
  1067. )
  1068. def get_source(self, fullname):
  1069. """Return None as there is no source code."""
  1070. return None
  1071. class ExtensionFileLoader(FileLoader, _LoaderBasics):
  1072. """Loader for extension modules.
  1073. The constructor is designed to work with FileFinder.
  1074. """
  1075. def __init__(self, name, path):
  1076. self.name = name
  1077. self.path = path
  1078. def __eq__(self, other):
  1079. return (self.__class__ == other.__class__ and
  1080. self.__dict__ == other.__dict__)
  1081. def __hash__(self):
  1082. return hash(self.name) ^ hash(self.path)
  1083. def create_module(self, spec):
  1084. """Create an uninitialized extension module"""
  1085. module = _bootstrap._call_with_frames_removed(
  1086. _imp.create_dynamic, spec)
  1087. _bootstrap._verbose_message('extension module {!r} loaded from {!r}',
  1088. spec.name, self.path)
  1089. return module
  1090. def exec_module(self, module):
  1091. """Initialize an extension module"""
  1092. _bootstrap._call_with_frames_removed(_imp.exec_dynamic, module)
  1093. _bootstrap._verbose_message('extension module {!r} executed from {!r}',
  1094. self.name, self.path)
  1095. def is_package(self, fullname):
  1096. """Return True if the extension module is a package."""
  1097. file_name = _path_split(self.path)[1]
  1098. return any(file_name == '__init__' + suffix
  1099. for suffix in EXTENSION_SUFFIXES)
  1100. def get_code(self, fullname):
  1101. """Return None as an extension module cannot create a code object."""
  1102. return None
  1103. def get_source(self, fullname):
  1104. """Return None as extension modules have no source code."""
  1105. return None
  1106. @_check_name
  1107. def get_filename(self, fullname):
  1108. """Return the path to the source file as found by the finder."""
  1109. return self.path
  1110. class _NamespacePath:
  1111. """Represents a namespace package's path. It uses the module name
  1112. to find its parent module, and from there it looks up the parent's
  1113. __path__. When this changes, the module's own path is recomputed,
  1114. using path_finder. For top-level modules, the parent module's path
  1115. is sys.path."""
  1116. # When invalidate_caches() is called, this epoch is incremented
  1117. # https://bugs.python.org/issue45703
  1118. _epoch = 0
  1119. def __init__(self, name, path, path_finder):
  1120. self._name = name
  1121. self._path = path
  1122. self._last_parent_path = tuple(self._get_parent_path())
  1123. self._last_epoch = self._epoch
  1124. self._path_finder = path_finder
  1125. def _find_parent_path_names(self):
  1126. """Returns a tuple of (parent-module-name, parent-path-attr-name)"""
  1127. parent, dot, me = self._name.rpartition('.')
  1128. if dot == '':
  1129. # This is a top-level module. sys.path contains the parent path.
  1130. return 'sys', 'path'
  1131. # Not a top-level module. parent-module.__path__ contains the
  1132. # parent path.
  1133. return parent, '__path__'
  1134. def _get_parent_path(self):
  1135. parent_module_name, path_attr_name = self._find_parent_path_names()
  1136. return getattr(sys.modules[parent_module_name], path_attr_name)
  1137. def _recalculate(self):
  1138. # If the parent's path has changed, recalculate _path
  1139. parent_path = tuple(self._get_parent_path()) # Make a copy
  1140. if parent_path != self._last_parent_path or self._epoch != self._last_epoch:
  1141. spec = self._path_finder(self._name, parent_path)
  1142. # Note that no changes are made if a loader is returned, but we
  1143. # do remember the new parent path
  1144. if spec is not None and spec.loader is None:
  1145. if spec.submodule_search_locations:
  1146. self._path = spec.submodule_search_locations
  1147. self._last_parent_path = parent_path # Save the copy
  1148. self._last_epoch = self._epoch
  1149. return self._path
  1150. def __iter__(self):
  1151. return iter(self._recalculate())
  1152. def __getitem__(self, index):
  1153. return self._recalculate()[index]
  1154. def __setitem__(self, index, path):
  1155. self._path[index] = path
  1156. def __len__(self):
  1157. return len(self._recalculate())
  1158. def __repr__(self):
  1159. return f'_NamespacePath({self._path!r})'
  1160. def __contains__(self, item):
  1161. return item in self._recalculate()
  1162. def append(self, item):
  1163. self._path.append(item)
  1164. # This class is actually exposed publicly in a namespace package's __loader__
  1165. # attribute, so it should be available through a non-private name.
  1166. # https://github.com/python/cpython/issues/92054
  1167. class NamespaceLoader:
  1168. def __init__(self, name, path, path_finder):
  1169. self._path = _NamespacePath(name, path, path_finder)
  1170. def is_package(self, fullname):
  1171. return True
  1172. def get_source(self, fullname):
  1173. return ''
  1174. def get_code(self, fullname):
  1175. return compile('', '<string>', 'exec', dont_inherit=True)
  1176. def create_module(self, spec):
  1177. """Use default semantics for module creation."""
  1178. def exec_module(self, module):
  1179. pass
  1180. def load_module(self, fullname):
  1181. """Load a namespace module.
  1182. This method is deprecated. Use exec_module() instead.
  1183. """
  1184. # The import system never calls this method.
  1185. _bootstrap._verbose_message('namespace module loaded with path {!r}',
  1186. self._path)
  1187. # Warning implemented in _load_module_shim().
  1188. return _bootstrap._load_module_shim(self, fullname)
  1189. def get_resource_reader(self, module):
  1190. from importlib.readers import NamespaceReader
  1191. return NamespaceReader(self._path)
  1192. # We use this exclusively in module_from_spec() for backward-compatibility.
  1193. _NamespaceLoader = NamespaceLoader
  1194. # Finders #####################################################################
  1195. class PathFinder:
  1196. """Meta path finder for sys.path and package __path__ attributes."""
  1197. @staticmethod
  1198. def invalidate_caches():
  1199. """Call the invalidate_caches() method on all path entry finders
  1200. stored in sys.path_importer_caches (where implemented)."""
  1201. for name, finder in list(sys.path_importer_cache.items()):
  1202. # Drop entry if finder name is a relative path. The current
  1203. # working directory may have changed.
  1204. if finder is None or not _path_isabs(name):
  1205. del sys.path_importer_cache[name]
  1206. elif hasattr(finder, 'invalidate_caches'):
  1207. finder.invalidate_caches()
  1208. # Also invalidate the caches of _NamespacePaths
  1209. # https://bugs.python.org/issue45703
  1210. _NamespacePath._epoch += 1
  1211. @staticmethod
  1212. def _path_hooks(path):
  1213. """Search sys.path_hooks for a finder for 'path'."""
  1214. if sys.path_hooks is not None and not sys.path_hooks:
  1215. _warnings.warn('sys.path_hooks is empty', ImportWarning)
  1216. for hook in sys.path_hooks:
  1217. try:
  1218. return hook(path)
  1219. except ImportError:
  1220. continue
  1221. else:
  1222. return None
  1223. @classmethod
  1224. def _path_importer_cache(cls, path):
  1225. """Get the finder for the path entry from sys.path_importer_cache.
  1226. If the path entry is not in the cache, find the appropriate finder
  1227. and cache it. If no finder is available, store None.
  1228. """
  1229. if path == '':
  1230. try:
  1231. path = _os.getcwd()
  1232. except FileNotFoundError:
  1233. # Don't cache the failure as the cwd can easily change to
  1234. # a valid directory later on.
  1235. return None
  1236. try:
  1237. finder = sys.path_importer_cache[path]
  1238. except KeyError:
  1239. finder = cls._path_hooks(path)
  1240. sys.path_importer_cache[path] = finder
  1241. return finder
  1242. @classmethod
  1243. def _get_spec(cls, fullname, path, target=None):
  1244. """Find the loader or namespace_path for this module/package name."""
  1245. # If this ends up being a namespace package, namespace_path is
  1246. # the list of paths that will become its __path__
  1247. namespace_path = []
  1248. for entry in path:
  1249. if not isinstance(entry, str):
  1250. continue
  1251. finder = cls._path_importer_cache(entry)
  1252. if finder is not None:
  1253. spec = finder.find_spec(fullname, target)
  1254. if spec is None:
  1255. continue
  1256. if spec.loader is not None:
  1257. return spec
  1258. portions = spec.submodule_search_locations
  1259. if portions is None:
  1260. raise ImportError('spec missing loader')
  1261. # This is possibly part of a namespace package.
  1262. # Remember these path entries (if any) for when we
  1263. # create a namespace package, and continue iterating
  1264. # on path.
  1265. namespace_path.extend(portions)
  1266. else:
  1267. spec = _bootstrap.ModuleSpec(fullname, None)
  1268. spec.submodule_search_locations = namespace_path
  1269. return spec
  1270. @classmethod
  1271. def find_spec(cls, fullname, path=None, target=None):
  1272. """Try to find a spec for 'fullname' on sys.path or 'path'.
  1273. The search is based on sys.path_hooks and sys.path_importer_cache.
  1274. """
  1275. if path is None:
  1276. path = sys.path
  1277. spec = cls._get_spec(fullname, path, target)
  1278. if spec is None:
  1279. return None
  1280. elif spec.loader is None:
  1281. namespace_path = spec.submodule_search_locations
  1282. if namespace_path:
  1283. # We found at least one namespace path. Return a spec which
  1284. # can create the namespace package.
  1285. spec.origin = None
  1286. spec.submodule_search_locations = _NamespacePath(fullname, namespace_path, cls._get_spec)
  1287. return spec
  1288. else:
  1289. return None
  1290. else:
  1291. return spec
  1292. @staticmethod
  1293. def find_distributions(*args, **kwargs):
  1294. """
  1295. Find distributions.
  1296. Return an iterable of all Distribution instances capable of
  1297. loading the metadata for packages matching ``context.name``
  1298. (or all names if ``None`` indicated) along the paths in the list
  1299. of directories ``context.path``.
  1300. """
  1301. from importlib.metadata import MetadataPathFinder
  1302. return MetadataPathFinder.find_distributions(*args, **kwargs)
  1303. class FileFinder:
  1304. """File-based finder.
  1305. Interactions with the file system are cached for performance, being
  1306. refreshed when the directory the finder is handling has been modified.
  1307. """
  1308. def __init__(self, path, *loader_details):
  1309. """Initialize with the path to search on and a variable number of
  1310. 2-tuples containing the loader and the file suffixes the loader
  1311. recognizes."""
  1312. loaders = []
  1313. for loader, suffixes in loader_details:
  1314. loaders.extend((suffix, loader) for suffix in suffixes)
  1315. self._loaders = loaders
  1316. # Base (directory) path
  1317. if not path or path == '.':
  1318. self.path = _os.getcwd()
  1319. else:
  1320. self.path = _path_abspath(path)
  1321. self._path_mtime = -1
  1322. self._path_cache = set()
  1323. self._relaxed_path_cache = set()
  1324. def invalidate_caches(self):
  1325. """Invalidate the directory mtime."""
  1326. self._path_mtime = -1
  1327. def _get_spec(self, loader_class, fullname, path, smsl, target):
  1328. loader = loader_class(fullname, path)
  1329. return spec_from_file_location(fullname, path, loader=loader,
  1330. submodule_search_locations=smsl)
  1331. def find_spec(self, fullname, target=None):
  1332. """Try to find a spec for the specified module.
  1333. Returns the matching spec, or None if not found.
  1334. """
  1335. is_namespace = False
  1336. tail_module = fullname.rpartition('.')[2]
  1337. try:
  1338. mtime = _path_stat(self.path or _os.getcwd()).st_mtime
  1339. except OSError:
  1340. mtime = -1
  1341. if mtime != self._path_mtime:
  1342. self._fill_cache()
  1343. self._path_mtime = mtime
  1344. # tail_module keeps the original casing, for __file__ and friends
  1345. if _relax_case():
  1346. cache = self._relaxed_path_cache
  1347. cache_module = tail_module.lower()
  1348. else:
  1349. cache = self._path_cache
  1350. cache_module = tail_module
  1351. # Check if the module is the name of a directory (and thus a package).
  1352. if cache_module in cache:
  1353. base_path = _path_join(self.path, tail_module)
  1354. for suffix, loader_class in self._loaders:
  1355. init_filename = '__init__' + suffix
  1356. full_path = _path_join(base_path, init_filename)
  1357. if _path_isfile(full_path):
  1358. return self._get_spec(loader_class, fullname, full_path, [base_path], target)
  1359. else:
  1360. # If a namespace package, return the path if we don't
  1361. # find a module in the next section.
  1362. is_namespace = _path_isdir(base_path)
  1363. # Check for a file w/ a proper suffix exists.
  1364. for suffix, loader_class in self._loaders:
  1365. try:
  1366. full_path = _path_join(self.path, tail_module + suffix)
  1367. except ValueError:
  1368. return None
  1369. _bootstrap._verbose_message('trying {}', full_path, verbosity=2)
  1370. if cache_module + suffix in cache:
  1371. if _path_isfile(full_path):
  1372. return self._get_spec(loader_class, fullname, full_path,
  1373. None, target)
  1374. if is_namespace:
  1375. _bootstrap._verbose_message('possible namespace for {}', base_path)
  1376. spec = _bootstrap.ModuleSpec(fullname, None)
  1377. spec.submodule_search_locations = [base_path]
  1378. return spec
  1379. return None
  1380. def _fill_cache(self):
  1381. """Fill the cache of potential modules and packages for this directory."""
  1382. path = self.path
  1383. try:
  1384. contents = _os.listdir(path or _os.getcwd())
  1385. except (FileNotFoundError, PermissionError, NotADirectoryError):
  1386. # Directory has either been removed, turned into a file, or made
  1387. # unreadable.
  1388. contents = []
  1389. # We store two cached versions, to handle runtime changes of the
  1390. # PYTHONCASEOK environment variable.
  1391. if not sys.platform.startswith('win'):
  1392. self._path_cache = set(contents)
  1393. else:
  1394. # Windows users can import modules with case-insensitive file
  1395. # suffixes (for legacy reasons). Make the suffix lowercase here
  1396. # so it's done once instead of for every import. This is safe as
  1397. # the specified suffixes to check against are always specified in a
  1398. # case-sensitive manner.
  1399. lower_suffix_contents = set()
  1400. for item in contents:
  1401. name, dot, suffix = item.partition('.')
  1402. if dot:
  1403. new_name = f'{name}.{suffix.lower()}'
  1404. else:
  1405. new_name = name
  1406. lower_suffix_contents.add(new_name)
  1407. self._path_cache = lower_suffix_contents
  1408. if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
  1409. self._relaxed_path_cache = {fn.lower() for fn in contents}
  1410. @classmethod
  1411. def path_hook(cls, *loader_details):
  1412. """A class method which returns a closure to use on sys.path_hook
  1413. which will return an instance using the specified loaders and the path
  1414. called on the closure.
  1415. If the path called on the closure is not a directory, ImportError is
  1416. raised.
  1417. """
  1418. def path_hook_for_FileFinder(path):
  1419. """Path hook for importlib.machinery.FileFinder."""
  1420. if not _path_isdir(path):
  1421. raise ImportError('only directories are supported', path=path)
  1422. return cls(path, *loader_details)
  1423. return path_hook_for_FileFinder
  1424. def __repr__(self):
  1425. return f'FileFinder({self.path!r})'
  1426. # Import setup ###############################################################
  1427. def _fix_up_module(ns, name, pathname, cpathname=None):
  1428. # This function is used by PyImport_ExecCodeModuleObject().
  1429. loader = ns.get('__loader__')
  1430. spec = ns.get('__spec__')
  1431. if not loader:
  1432. if spec:
  1433. loader = spec.loader
  1434. elif pathname == cpathname:
  1435. loader = SourcelessFileLoader(name, pathname)
  1436. else:
  1437. loader = SourceFileLoader(name, pathname)
  1438. if not spec:
  1439. spec = spec_from_file_location(name, pathname, loader=loader)
  1440. if cpathname:
  1441. spec.cached = _path_abspath(cpathname)
  1442. try:
  1443. ns['__spec__'] = spec
  1444. ns['__loader__'] = loader
  1445. ns['__file__'] = pathname
  1446. ns['__cached__'] = cpathname
  1447. except Exception:
  1448. # Not important enough to report.
  1449. pass
  1450. def _get_supported_file_loaders():
  1451. """Returns a list of file-based module loaders.
  1452. Each item is a tuple (loader, suffixes).
  1453. """
  1454. extensions = ExtensionFileLoader, _imp.extension_suffixes()
  1455. source = SourceFileLoader, SOURCE_SUFFIXES
  1456. bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES
  1457. return [extensions, source, bytecode]
  1458. def _set_bootstrap_module(_bootstrap_module):
  1459. global _bootstrap
  1460. _bootstrap = _bootstrap_module
  1461. def _install(_bootstrap_module):
  1462. """Install the path-based import components."""
  1463. _set_bootstrap_module(_bootstrap_module)
  1464. supported_loaders = _get_supported_file_loaders()
  1465. sys.path_hooks.extend([FileFinder.path_hook(*supported_loaders)])
  1466. sys.meta_path.append(PathFinder)