@rowstile/cli-linux-x64 0.1.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (565) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +5 -0
  3. package/package.json +26 -0
  4. package/python/bin/python3.13 +0 -0
  5. package/python/bin/python3.13-config +122 -0
  6. package/python/lib/libpython3.13.so.1.0 +0 -0
  7. package/python/lib/libpython3.so +0 -0
  8. package/python/lib/python3.13/LICENSE.txt +277 -0
  9. package/python/lib/python3.13/__future__.py +147 -0
  10. package/python/lib/python3.13/__hello__.py +16 -0
  11. package/python/lib/python3.13/_aix_support.py +108 -0
  12. package/python/lib/python3.13/_android_support.py +192 -0
  13. package/python/lib/python3.13/_apple_support.py +66 -0
  14. package/python/lib/python3.13/_collections_abc.py +1187 -0
  15. package/python/lib/python3.13/_colorize.py +119 -0
  16. package/python/lib/python3.13/_compat_pickle.py +251 -0
  17. package/python/lib/python3.13/_compression.py +162 -0
  18. package/python/lib/python3.13/_ios_support.py +71 -0
  19. package/python/lib/python3.13/_markupbase.py +396 -0
  20. package/python/lib/python3.13/_opcode_metadata.py +343 -0
  21. package/python/lib/python3.13/_osx_support.py +579 -0
  22. package/python/lib/python3.13/_py_abc.py +147 -0
  23. package/python/lib/python3.13/_pydatetime.py +2640 -0
  24. package/python/lib/python3.13/_pydecimal.py +6356 -0
  25. package/python/lib/python3.13/_pyio.py +2714 -0
  26. package/python/lib/python3.13/_pylong.py +363 -0
  27. package/python/lib/python3.13/_pyrepl/__init__.py +19 -0
  28. package/python/lib/python3.13/_pyrepl/__main__.py +10 -0
  29. package/python/lib/python3.13/_pyrepl/_minimal_curses.py +68 -0
  30. package/python/lib/python3.13/_pyrepl/_threading_handler.py +74 -0
  31. package/python/lib/python3.13/_pyrepl/base_eventqueue.py +110 -0
  32. package/python/lib/python3.13/_pyrepl/commands.py +492 -0
  33. package/python/lib/python3.13/_pyrepl/completing_reader.py +295 -0
  34. package/python/lib/python3.13/_pyrepl/console.py +229 -0
  35. package/python/lib/python3.13/_pyrepl/curses.py +33 -0
  36. package/python/lib/python3.13/_pyrepl/fancy_termios.py +82 -0
  37. package/python/lib/python3.13/_pyrepl/historical_reader.py +419 -0
  38. package/python/lib/python3.13/_pyrepl/input.py +114 -0
  39. package/python/lib/python3.13/_pyrepl/keymap.py +213 -0
  40. package/python/lib/python3.13/_pyrepl/main.py +59 -0
  41. package/python/lib/python3.13/_pyrepl/mypy.ini +29 -0
  42. package/python/lib/python3.13/_pyrepl/pager.py +175 -0
  43. package/python/lib/python3.13/_pyrepl/reader.py +764 -0
  44. package/python/lib/python3.13/_pyrepl/readline.py +599 -0
  45. package/python/lib/python3.13/_pyrepl/simple_interact.py +180 -0
  46. package/python/lib/python3.13/_pyrepl/trace.py +21 -0
  47. package/python/lib/python3.13/_pyrepl/types.py +10 -0
  48. package/python/lib/python3.13/_pyrepl/unix_console.py +852 -0
  49. package/python/lib/python3.13/_pyrepl/unix_eventqueue.py +76 -0
  50. package/python/lib/python3.13/_pyrepl/utils.py +83 -0
  51. package/python/lib/python3.13/_pyrepl/windows_console.py +687 -0
  52. package/python/lib/python3.13/_pyrepl/windows_eventqueue.py +42 -0
  53. package/python/lib/python3.13/_sitebuiltins.py +91 -0
  54. package/python/lib/python3.13/_strptime.py +800 -0
  55. package/python/lib/python3.13/_sysconfigdata__linux_x86_64-linux-gnu.py +1079 -0
  56. package/python/lib/python3.13/_threading_local.py +120 -0
  57. package/python/lib/python3.13/_weakrefset.py +205 -0
  58. package/python/lib/python3.13/abc.py +188 -0
  59. package/python/lib/python3.13/antigravity.py +17 -0
  60. package/python/lib/python3.13/argparse.py +2690 -0
  61. package/python/lib/python3.13/ast.py +1865 -0
  62. package/python/lib/python3.13/asyncio/__init__.py +47 -0
  63. package/python/lib/python3.13/asyncio/__main__.py +211 -0
  64. package/python/lib/python3.13/asyncio/base_events.py +2086 -0
  65. package/python/lib/python3.13/asyncio/base_futures.py +67 -0
  66. package/python/lib/python3.13/asyncio/base_subprocess.py +312 -0
  67. package/python/lib/python3.13/asyncio/base_tasks.py +94 -0
  68. package/python/lib/python3.13/asyncio/constants.py +41 -0
  69. package/python/lib/python3.13/asyncio/coroutines.py +109 -0
  70. package/python/lib/python3.13/asyncio/events.py +885 -0
  71. package/python/lib/python3.13/asyncio/exceptions.py +62 -0
  72. package/python/lib/python3.13/asyncio/format_helpers.py +84 -0
  73. package/python/lib/python3.13/asyncio/futures.py +425 -0
  74. package/python/lib/python3.13/asyncio/locks.py +617 -0
  75. package/python/lib/python3.13/asyncio/log.py +7 -0
  76. package/python/lib/python3.13/asyncio/mixins.py +21 -0
  77. package/python/lib/python3.13/asyncio/proactor_events.py +891 -0
  78. package/python/lib/python3.13/asyncio/protocols.py +216 -0
  79. package/python/lib/python3.13/asyncio/queues.py +309 -0
  80. package/python/lib/python3.13/asyncio/runners.py +217 -0
  81. package/python/lib/python3.13/asyncio/selector_events.py +1328 -0
  82. package/python/lib/python3.13/asyncio/sslproto.py +929 -0
  83. package/python/lib/python3.13/asyncio/staggered.py +174 -0
  84. package/python/lib/python3.13/asyncio/streams.py +787 -0
  85. package/python/lib/python3.13/asyncio/subprocess.py +229 -0
  86. package/python/lib/python3.13/asyncio/taskgroups.py +278 -0
  87. package/python/lib/python3.13/asyncio/tasks.py +1121 -0
  88. package/python/lib/python3.13/asyncio/threads.py +26 -0
  89. package/python/lib/python3.13/asyncio/timeouts.py +185 -0
  90. package/python/lib/python3.13/asyncio/transports.py +337 -0
  91. package/python/lib/python3.13/asyncio/trsock.py +98 -0
  92. package/python/lib/python3.13/asyncio/unix_events.py +1550 -0
  93. package/python/lib/python3.13/asyncio/windows_events.py +906 -0
  94. package/python/lib/python3.13/asyncio/windows_utils.py +181 -0
  95. package/python/lib/python3.13/base64.py +628 -0
  96. package/python/lib/python3.13/bdb.py +973 -0
  97. package/python/lib/python3.13/bisect.py +118 -0
  98. package/python/lib/python3.13/bz2.py +352 -0
  99. package/python/lib/python3.13/cProfile.py +197 -0
  100. package/python/lib/python3.13/calendar.py +813 -0
  101. package/python/lib/python3.13/cmd.py +409 -0
  102. package/python/lib/python3.13/code.py +386 -0
  103. package/python/lib/python3.13/codecs.py +1132 -0
  104. package/python/lib/python3.13/codeop.py +155 -0
  105. package/python/lib/python3.13/collections/__init__.py +1603 -0
  106. package/python/lib/python3.13/colorsys.py +166 -0
  107. package/python/lib/python3.13/compileall.py +470 -0
  108. package/python/lib/python3.13/concurrent/__init__.py +1 -0
  109. package/python/lib/python3.13/concurrent/futures/__init__.py +54 -0
  110. package/python/lib/python3.13/concurrent/futures/_base.py +660 -0
  111. package/python/lib/python3.13/concurrent/futures/process.py +892 -0
  112. package/python/lib/python3.13/concurrent/futures/thread.py +240 -0
  113. package/python/lib/python3.13/configparser.py +1396 -0
  114. package/python/lib/python3.13/contextlib.py +814 -0
  115. package/python/lib/python3.13/contextvars.py +4 -0
  116. package/python/lib/python3.13/copy.py +306 -0
  117. package/python/lib/python3.13/copyreg.py +217 -0
  118. package/python/lib/python3.13/csv.py +527 -0
  119. package/python/lib/python3.13/ctypes/__init__.py +605 -0
  120. package/python/lib/python3.13/ctypes/_aix.py +327 -0
  121. package/python/lib/python3.13/ctypes/_endian.py +78 -0
  122. package/python/lib/python3.13/ctypes/macholib/README.ctypes +7 -0
  123. package/python/lib/python3.13/ctypes/macholib/__init__.py +9 -0
  124. package/python/lib/python3.13/ctypes/macholib/dyld.py +165 -0
  125. package/python/lib/python3.13/ctypes/macholib/dylib.py +42 -0
  126. package/python/lib/python3.13/ctypes/macholib/fetch_macholib +2 -0
  127. package/python/lib/python3.13/ctypes/macholib/fetch_macholib.bat +1 -0
  128. package/python/lib/python3.13/ctypes/macholib/framework.py +42 -0
  129. package/python/lib/python3.13/ctypes/util.py +387 -0
  130. package/python/lib/python3.13/ctypes/wintypes.py +202 -0
  131. package/python/lib/python3.13/curses/__init__.py +101 -0
  132. package/python/lib/python3.13/curses/ascii.py +99 -0
  133. package/python/lib/python3.13/curses/has_key.py +192 -0
  134. package/python/lib/python3.13/curses/panel.py +6 -0
  135. package/python/lib/python3.13/curses/textpad.py +236 -0
  136. package/python/lib/python3.13/dataclasses.py +1679 -0
  137. package/python/lib/python3.13/datetime.py +9 -0
  138. package/python/lib/python3.13/dbm/__init__.py +194 -0
  139. package/python/lib/python3.13/dbm/dumb.py +319 -0
  140. package/python/lib/python3.13/dbm/gnu.py +3 -0
  141. package/python/lib/python3.13/dbm/ndbm.py +3 -0
  142. package/python/lib/python3.13/dbm/sqlite3.py +144 -0
  143. package/python/lib/python3.13/decimal.py +109 -0
  144. package/python/lib/python3.13/difflib.py +2058 -0
  145. package/python/lib/python3.13/dis.py +1075 -0
  146. package/python/lib/python3.13/doctest.py +2919 -0
  147. package/python/lib/python3.13/email/__init__.py +61 -0
  148. package/python/lib/python3.13/email/_encoded_words.py +233 -0
  149. package/python/lib/python3.13/email/_header_value_parser.py +3153 -0
  150. package/python/lib/python3.13/email/_parseaddr.py +563 -0
  151. package/python/lib/python3.13/email/_policybase.py +382 -0
  152. package/python/lib/python3.13/email/architecture.rst +216 -0
  153. package/python/lib/python3.13/email/base64mime.py +115 -0
  154. package/python/lib/python3.13/email/charset.py +396 -0
  155. package/python/lib/python3.13/email/contentmanager.py +254 -0
  156. package/python/lib/python3.13/email/encoders.py +65 -0
  157. package/python/lib/python3.13/email/errors.py +117 -0
  158. package/python/lib/python3.13/email/feedparser.py +536 -0
  159. package/python/lib/python3.13/email/generator.py +530 -0
  160. package/python/lib/python3.13/email/header.py +582 -0
  161. package/python/lib/python3.13/email/headerregistry.py +618 -0
  162. package/python/lib/python3.13/email/iterators.py +68 -0
  163. package/python/lib/python3.13/email/message.py +1217 -0
  164. package/python/lib/python3.13/email/mime/__init__.py +0 -0
  165. package/python/lib/python3.13/email/mime/application.py +37 -0
  166. package/python/lib/python3.13/email/mime/audio.py +97 -0
  167. package/python/lib/python3.13/email/mime/base.py +29 -0
  168. package/python/lib/python3.13/email/mime/image.py +152 -0
  169. package/python/lib/python3.13/email/mime/message.py +33 -0
  170. package/python/lib/python3.13/email/mime/multipart.py +47 -0
  171. package/python/lib/python3.13/email/mime/nonmultipart.py +21 -0
  172. package/python/lib/python3.13/email/mime/text.py +40 -0
  173. package/python/lib/python3.13/email/parser.py +127 -0
  174. package/python/lib/python3.13/email/policy.py +232 -0
  175. package/python/lib/python3.13/email/quoprimime.py +300 -0
  176. package/python/lib/python3.13/email/utils.py +497 -0
  177. package/python/lib/python3.13/encodings/__init__.py +179 -0
  178. package/python/lib/python3.13/encodings/__pycache__/__init__.cpython-313.pyc +0 -0
  179. package/python/lib/python3.13/encodings/__pycache__/aliases.cpython-313.pyc +0 -0
  180. package/python/lib/python3.13/encodings/__pycache__/utf_8.cpython-313.pyc +0 -0
  181. package/python/lib/python3.13/encodings/aliases.py +560 -0
  182. package/python/lib/python3.13/encodings/ascii.py +50 -0
  183. package/python/lib/python3.13/encodings/base64_codec.py +55 -0
  184. package/python/lib/python3.13/encodings/big5.py +39 -0
  185. package/python/lib/python3.13/encodings/big5hkscs.py +39 -0
  186. package/python/lib/python3.13/encodings/bz2_codec.py +78 -0
  187. package/python/lib/python3.13/encodings/charmap.py +69 -0
  188. package/python/lib/python3.13/encodings/cp037.py +307 -0
  189. package/python/lib/python3.13/encodings/cp1006.py +307 -0
  190. package/python/lib/python3.13/encodings/cp1026.py +307 -0
  191. package/python/lib/python3.13/encodings/cp1125.py +698 -0
  192. package/python/lib/python3.13/encodings/cp1140.py +307 -0
  193. package/python/lib/python3.13/encodings/cp1250.py +307 -0
  194. package/python/lib/python3.13/encodings/cp1251.py +307 -0
  195. package/python/lib/python3.13/encodings/cp1252.py +307 -0
  196. package/python/lib/python3.13/encodings/cp1253.py +307 -0
  197. package/python/lib/python3.13/encodings/cp1254.py +307 -0
  198. package/python/lib/python3.13/encodings/cp1255.py +307 -0
  199. package/python/lib/python3.13/encodings/cp1256.py +307 -0
  200. package/python/lib/python3.13/encodings/cp1257.py +307 -0
  201. package/python/lib/python3.13/encodings/cp1258.py +307 -0
  202. package/python/lib/python3.13/encodings/cp273.py +307 -0
  203. package/python/lib/python3.13/encodings/cp424.py +307 -0
  204. package/python/lib/python3.13/encodings/cp437.py +698 -0
  205. package/python/lib/python3.13/encodings/cp500.py +307 -0
  206. package/python/lib/python3.13/encodings/cp720.py +309 -0
  207. package/python/lib/python3.13/encodings/cp737.py +698 -0
  208. package/python/lib/python3.13/encodings/cp775.py +697 -0
  209. package/python/lib/python3.13/encodings/cp850.py +698 -0
  210. package/python/lib/python3.13/encodings/cp852.py +698 -0
  211. package/python/lib/python3.13/encodings/cp855.py +698 -0
  212. package/python/lib/python3.13/encodings/cp856.py +307 -0
  213. package/python/lib/python3.13/encodings/cp857.py +694 -0
  214. package/python/lib/python3.13/encodings/cp858.py +698 -0
  215. package/python/lib/python3.13/encodings/cp860.py +698 -0
  216. package/python/lib/python3.13/encodings/cp861.py +698 -0
  217. package/python/lib/python3.13/encodings/cp862.py +698 -0
  218. package/python/lib/python3.13/encodings/cp863.py +698 -0
  219. package/python/lib/python3.13/encodings/cp864.py +690 -0
  220. package/python/lib/python3.13/encodings/cp865.py +698 -0
  221. package/python/lib/python3.13/encodings/cp866.py +698 -0
  222. package/python/lib/python3.13/encodings/cp869.py +689 -0
  223. package/python/lib/python3.13/encodings/cp874.py +307 -0
  224. package/python/lib/python3.13/encodings/cp875.py +307 -0
  225. package/python/lib/python3.13/encodings/cp932.py +39 -0
  226. package/python/lib/python3.13/encodings/cp949.py +39 -0
  227. package/python/lib/python3.13/encodings/cp950.py +39 -0
  228. package/python/lib/python3.13/encodings/euc_jis_2004.py +39 -0
  229. package/python/lib/python3.13/encodings/euc_jisx0213.py +39 -0
  230. package/python/lib/python3.13/encodings/euc_jp.py +39 -0
  231. package/python/lib/python3.13/encodings/euc_kr.py +39 -0
  232. package/python/lib/python3.13/encodings/gb18030.py +39 -0
  233. package/python/lib/python3.13/encodings/gb2312.py +39 -0
  234. package/python/lib/python3.13/encodings/gbk.py +39 -0
  235. package/python/lib/python3.13/encodings/hex_codec.py +55 -0
  236. package/python/lib/python3.13/encodings/hp_roman8.py +314 -0
  237. package/python/lib/python3.13/encodings/hz.py +39 -0
  238. package/python/lib/python3.13/encodings/idna.py +387 -0
  239. package/python/lib/python3.13/encodings/iso2022_jp.py +39 -0
  240. package/python/lib/python3.13/encodings/iso2022_jp_1.py +39 -0
  241. package/python/lib/python3.13/encodings/iso2022_jp_2.py +39 -0
  242. package/python/lib/python3.13/encodings/iso2022_jp_2004.py +39 -0
  243. package/python/lib/python3.13/encodings/iso2022_jp_3.py +39 -0
  244. package/python/lib/python3.13/encodings/iso2022_jp_ext.py +39 -0
  245. package/python/lib/python3.13/encodings/iso2022_kr.py +39 -0
  246. package/python/lib/python3.13/encodings/iso8859_1.py +307 -0
  247. package/python/lib/python3.13/encodings/iso8859_10.py +307 -0
  248. package/python/lib/python3.13/encodings/iso8859_11.py +307 -0
  249. package/python/lib/python3.13/encodings/iso8859_13.py +307 -0
  250. package/python/lib/python3.13/encodings/iso8859_14.py +307 -0
  251. package/python/lib/python3.13/encodings/iso8859_15.py +307 -0
  252. package/python/lib/python3.13/encodings/iso8859_16.py +307 -0
  253. package/python/lib/python3.13/encodings/iso8859_2.py +307 -0
  254. package/python/lib/python3.13/encodings/iso8859_3.py +307 -0
  255. package/python/lib/python3.13/encodings/iso8859_4.py +307 -0
  256. package/python/lib/python3.13/encodings/iso8859_5.py +307 -0
  257. package/python/lib/python3.13/encodings/iso8859_6.py +307 -0
  258. package/python/lib/python3.13/encodings/iso8859_7.py +307 -0
  259. package/python/lib/python3.13/encodings/iso8859_8.py +307 -0
  260. package/python/lib/python3.13/encodings/iso8859_9.py +307 -0
  261. package/python/lib/python3.13/encodings/johab.py +39 -0
  262. package/python/lib/python3.13/encodings/koi8_r.py +307 -0
  263. package/python/lib/python3.13/encodings/koi8_t.py +308 -0
  264. package/python/lib/python3.13/encodings/koi8_u.py +307 -0
  265. package/python/lib/python3.13/encodings/kz1048.py +307 -0
  266. package/python/lib/python3.13/encodings/latin_1.py +50 -0
  267. package/python/lib/python3.13/encodings/mac_arabic.py +698 -0
  268. package/python/lib/python3.13/encodings/mac_croatian.py +307 -0
  269. package/python/lib/python3.13/encodings/mac_cyrillic.py +307 -0
  270. package/python/lib/python3.13/encodings/mac_farsi.py +307 -0
  271. package/python/lib/python3.13/encodings/mac_greek.py +307 -0
  272. package/python/lib/python3.13/encodings/mac_iceland.py +307 -0
  273. package/python/lib/python3.13/encodings/mac_latin2.py +312 -0
  274. package/python/lib/python3.13/encodings/mac_roman.py +307 -0
  275. package/python/lib/python3.13/encodings/mac_romanian.py +307 -0
  276. package/python/lib/python3.13/encodings/mac_turkish.py +307 -0
  277. package/python/lib/python3.13/encodings/mbcs.py +47 -0
  278. package/python/lib/python3.13/encodings/oem.py +41 -0
  279. package/python/lib/python3.13/encodings/palmos.py +308 -0
  280. package/python/lib/python3.13/encodings/ptcp154.py +312 -0
  281. package/python/lib/python3.13/encodings/punycode.py +253 -0
  282. package/python/lib/python3.13/encodings/quopri_codec.py +56 -0
  283. package/python/lib/python3.13/encodings/raw_unicode_escape.py +46 -0
  284. package/python/lib/python3.13/encodings/rot_13.py +113 -0
  285. package/python/lib/python3.13/encodings/shift_jis.py +39 -0
  286. package/python/lib/python3.13/encodings/shift_jis_2004.py +39 -0
  287. package/python/lib/python3.13/encodings/shift_jisx0213.py +39 -0
  288. package/python/lib/python3.13/encodings/tis_620.py +307 -0
  289. package/python/lib/python3.13/encodings/undefined.py +49 -0
  290. package/python/lib/python3.13/encodings/unicode_escape.py +46 -0
  291. package/python/lib/python3.13/encodings/utf_16.py +155 -0
  292. package/python/lib/python3.13/encodings/utf_16_be.py +42 -0
  293. package/python/lib/python3.13/encodings/utf_16_le.py +42 -0
  294. package/python/lib/python3.13/encodings/utf_32.py +150 -0
  295. package/python/lib/python3.13/encodings/utf_32_be.py +37 -0
  296. package/python/lib/python3.13/encodings/utf_32_le.py +37 -0
  297. package/python/lib/python3.13/encodings/utf_7.py +38 -0
  298. package/python/lib/python3.13/encodings/utf_8.py +42 -0
  299. package/python/lib/python3.13/encodings/utf_8_sig.py +130 -0
  300. package/python/lib/python3.13/encodings/uu_codec.py +103 -0
  301. package/python/lib/python3.13/encodings/zlib_codec.py +77 -0
  302. package/python/lib/python3.13/enum.py +2183 -0
  303. package/python/lib/python3.13/filecmp.py +320 -0
  304. package/python/lib/python3.13/fileinput.py +442 -0
  305. package/python/lib/python3.13/fnmatch.py +192 -0
  306. package/python/lib/python3.13/fractions.py +1043 -0
  307. package/python/lib/python3.13/ftplib.py +975 -0
  308. package/python/lib/python3.13/functools.py +1036 -0
  309. package/python/lib/python3.13/genericpath.py +200 -0
  310. package/python/lib/python3.13/getopt.py +215 -0
  311. package/python/lib/python3.13/getpass.py +192 -0
  312. package/python/lib/python3.13/gettext.py +657 -0
  313. package/python/lib/python3.13/glob.py +572 -0
  314. package/python/lib/python3.13/graphlib.py +250 -0
  315. package/python/lib/python3.13/gzip.py +693 -0
  316. package/python/lib/python3.13/hashlib.py +255 -0
  317. package/python/lib/python3.13/heapq.py +603 -0
  318. package/python/lib/python3.13/hmac.py +220 -0
  319. package/python/lib/python3.13/html/__init__.py +132 -0
  320. package/python/lib/python3.13/html/entities.py +2513 -0
  321. package/python/lib/python3.13/html/parser.py +583 -0
  322. package/python/lib/python3.13/http/__init__.py +202 -0
  323. package/python/lib/python3.13/http/client.py +1598 -0
  324. package/python/lib/python3.13/http/cookiejar.py +2122 -0
  325. package/python/lib/python3.13/http/cookies.py +635 -0
  326. package/python/lib/python3.13/http/server.py +1355 -0
  327. package/python/lib/python3.13/imaplib.py +1769 -0
  328. package/python/lib/python3.13/importlib/__init__.py +136 -0
  329. package/python/lib/python3.13/importlib/_abc.py +39 -0
  330. package/python/lib/python3.13/importlib/_bootstrap.py +1559 -0
  331. package/python/lib/python3.13/importlib/_bootstrap_external.py +1826 -0
  332. package/python/lib/python3.13/importlib/abc.py +243 -0
  333. package/python/lib/python3.13/importlib/machinery.py +21 -0
  334. package/python/lib/python3.13/importlib/metadata/__init__.py +1093 -0
  335. package/python/lib/python3.13/importlib/metadata/_adapters.py +89 -0
  336. package/python/lib/python3.13/importlib/metadata/_collections.py +30 -0
  337. package/python/lib/python3.13/importlib/metadata/_functools.py +104 -0
  338. package/python/lib/python3.13/importlib/metadata/_itertools.py +73 -0
  339. package/python/lib/python3.13/importlib/metadata/_meta.py +67 -0
  340. package/python/lib/python3.13/importlib/metadata/_text.py +99 -0
  341. package/python/lib/python3.13/importlib/metadata/diagnose.py +21 -0
  342. package/python/lib/python3.13/importlib/readers.py +12 -0
  343. package/python/lib/python3.13/importlib/resources/__init__.py +43 -0
  344. package/python/lib/python3.13/importlib/resources/_adapters.py +168 -0
  345. package/python/lib/python3.13/importlib/resources/_common.py +211 -0
  346. package/python/lib/python3.13/importlib/resources/_functional.py +81 -0
  347. package/python/lib/python3.13/importlib/resources/_itertools.py +38 -0
  348. package/python/lib/python3.13/importlib/resources/abc.py +173 -0
  349. package/python/lib/python3.13/importlib/resources/readers.py +203 -0
  350. package/python/lib/python3.13/importlib/resources/simple.py +106 -0
  351. package/python/lib/python3.13/importlib/simple.py +14 -0
  352. package/python/lib/python3.13/importlib/util.py +274 -0
  353. package/python/lib/python3.13/inspect.py +3479 -0
  354. package/python/lib/python3.13/io.py +99 -0
  355. package/python/lib/python3.13/ipaddress.py +2440 -0
  356. package/python/lib/python3.13/json/__init__.py +365 -0
  357. package/python/lib/python3.13/json/decoder.py +364 -0
  358. package/python/lib/python3.13/json/encoder.py +446 -0
  359. package/python/lib/python3.13/json/scanner.py +73 -0
  360. package/python/lib/python3.13/json/tool.py +90 -0
  361. package/python/lib/python3.13/keyword.py +64 -0
  362. package/python/lib/python3.13/lib-dynload/.empty +0 -0
  363. package/python/lib/python3.13/lib-dynload/_dbm.cpython-313-x86_64-linux-gnu.so +0 -0
  364. package/python/lib/python3.13/linecache.py +236 -0
  365. package/python/lib/python3.13/locale.py +1987 -0
  366. package/python/lib/python3.13/logging/__init__.py +2330 -0
  367. package/python/lib/python3.13/logging/config.py +1080 -0
  368. package/python/lib/python3.13/logging/handlers.py +1629 -0
  369. package/python/lib/python3.13/lzma.py +364 -0
  370. package/python/lib/python3.13/mailbox.py +2219 -0
  371. package/python/lib/python3.13/mimetypes.py +679 -0
  372. package/python/lib/python3.13/modulefinder.py +671 -0
  373. package/python/lib/python3.13/multiprocessing/__init__.py +37 -0
  374. package/python/lib/python3.13/multiprocessing/connection.py +1216 -0
  375. package/python/lib/python3.13/multiprocessing/context.py +383 -0
  376. package/python/lib/python3.13/multiprocessing/dummy/__init__.py +126 -0
  377. package/python/lib/python3.13/multiprocessing/dummy/connection.py +75 -0
  378. package/python/lib/python3.13/multiprocessing/forkserver.py +373 -0
  379. package/python/lib/python3.13/multiprocessing/heap.py +337 -0
  380. package/python/lib/python3.13/multiprocessing/managers.py +1397 -0
  381. package/python/lib/python3.13/multiprocessing/pool.py +957 -0
  382. package/python/lib/python3.13/multiprocessing/popen_fork.py +97 -0
  383. package/python/lib/python3.13/multiprocessing/popen_forkserver.py +74 -0
  384. package/python/lib/python3.13/multiprocessing/popen_spawn_posix.py +76 -0
  385. package/python/lib/python3.13/multiprocessing/popen_spawn_win32.py +147 -0
  386. package/python/lib/python3.13/multiprocessing/process.py +436 -0
  387. package/python/lib/python3.13/multiprocessing/queues.py +399 -0
  388. package/python/lib/python3.13/multiprocessing/reduction.py +281 -0
  389. package/python/lib/python3.13/multiprocessing/resource_sharer.py +154 -0
  390. package/python/lib/python3.13/multiprocessing/resource_tracker.py +499 -0
  391. package/python/lib/python3.13/multiprocessing/shared_memory.py +544 -0
  392. package/python/lib/python3.13/multiprocessing/sharedctypes.py +240 -0
  393. package/python/lib/python3.13/multiprocessing/spawn.py +307 -0
  394. package/python/lib/python3.13/multiprocessing/synchronize.py +404 -0
  395. package/python/lib/python3.13/multiprocessing/util.py +562 -0
  396. package/python/lib/python3.13/netrc.py +199 -0
  397. package/python/lib/python3.13/ntpath.py +872 -0
  398. package/python/lib/python3.13/nturl2path.py +69 -0
  399. package/python/lib/python3.13/numbers.py +427 -0
  400. package/python/lib/python3.13/opcode.py +115 -0
  401. package/python/lib/python3.13/operator.py +467 -0
  402. package/python/lib/python3.13/optparse.py +1681 -0
  403. package/python/lib/python3.13/os.py +1184 -0
  404. package/python/lib/python3.13/pathlib/__init__.py +12 -0
  405. package/python/lib/python3.13/pathlib/_abc.py +930 -0
  406. package/python/lib/python3.13/pathlib/_local.py +861 -0
  407. package/python/lib/python3.13/pdb.py +2550 -0
  408. package/python/lib/python3.13/pickle.py +1860 -0
  409. package/python/lib/python3.13/pickletools.py +2904 -0
  410. package/python/lib/python3.13/pkgutil.py +529 -0
  411. package/python/lib/python3.13/platform.py +1454 -0
  412. package/python/lib/python3.13/plistlib.py +948 -0
  413. package/python/lib/python3.13/poplib.py +477 -0
  414. package/python/lib/python3.13/posixpath.py +578 -0
  415. package/python/lib/python3.13/pprint.py +658 -0
  416. package/python/lib/python3.13/profile.py +616 -0
  417. package/python/lib/python3.13/pstats.py +778 -0
  418. package/python/lib/python3.13/pty.py +211 -0
  419. package/python/lib/python3.13/py_compile.py +212 -0
  420. package/python/lib/python3.13/pyclbr.py +314 -0
  421. package/python/lib/python3.13/pydoc.py +2861 -0
  422. package/python/lib/python3.13/queue.py +383 -0
  423. package/python/lib/python3.13/quopri.py +237 -0
  424. package/python/lib/python3.13/random.py +1078 -0
  425. package/python/lib/python3.13/re/__init__.py +428 -0
  426. package/python/lib/python3.13/re/_casefix.py +106 -0
  427. package/python/lib/python3.13/re/_compiler.py +768 -0
  428. package/python/lib/python3.13/re/_constants.py +222 -0
  429. package/python/lib/python3.13/re/_parser.py +1081 -0
  430. package/python/lib/python3.13/reprlib.py +230 -0
  431. package/python/lib/python3.13/rlcompleter.py +222 -0
  432. package/python/lib/python3.13/runpy.py +326 -0
  433. package/python/lib/python3.13/sched.py +167 -0
  434. package/python/lib/python3.13/secrets.py +71 -0
  435. package/python/lib/python3.13/selectors.py +603 -0
  436. package/python/lib/python3.13/shelve.py +250 -0
  437. package/python/lib/python3.13/shlex.py +345 -0
  438. package/python/lib/python3.13/shutil.py +1569 -0
  439. package/python/lib/python3.13/signal.py +94 -0
  440. package/python/lib/python3.13/site.py +773 -0
  441. package/python/lib/python3.13/smtplib.py +1123 -0
  442. package/python/lib/python3.13/socket.py +988 -0
  443. package/python/lib/python3.13/socketserver.py +863 -0
  444. package/python/lib/python3.13/sqlite3/__init__.py +70 -0
  445. package/python/lib/python3.13/sqlite3/__main__.py +139 -0
  446. package/python/lib/python3.13/sqlite3/dbapi2.py +108 -0
  447. package/python/lib/python3.13/sqlite3/dump.py +118 -0
  448. package/python/lib/python3.13/sre_compile.py +7 -0
  449. package/python/lib/python3.13/sre_constants.py +7 -0
  450. package/python/lib/python3.13/sre_parse.py +7 -0
  451. package/python/lib/python3.13/ssl.py +1541 -0
  452. package/python/lib/python3.13/stat.py +212 -0
  453. package/python/lib/python3.13/statistics.py +1817 -0
  454. package/python/lib/python3.13/string.py +314 -0
  455. package/python/lib/python3.13/stringprep.py +272 -0
  456. package/python/lib/python3.13/struct.py +15 -0
  457. package/python/lib/python3.13/subprocess.py +2258 -0
  458. package/python/lib/python3.13/symtable.py +414 -0
  459. package/python/lib/python3.13/sysconfig/__init__.py +734 -0
  460. package/python/lib/python3.13/sysconfig/__main__.py +248 -0
  461. package/python/lib/python3.13/tabnanny.py +340 -0
  462. package/python/lib/python3.13/tarfile.py +3136 -0
  463. package/python/lib/python3.13/tempfile.py +958 -0
  464. package/python/lib/python3.13/textwrap.py +497 -0
  465. package/python/lib/python3.13/this.py +28 -0
  466. package/python/lib/python3.13/threading.py +1602 -0
  467. package/python/lib/python3.13/timeit.py +381 -0
  468. package/python/lib/python3.13/token.py +141 -0
  469. package/python/lib/python3.13/tokenize.py +592 -0
  470. package/python/lib/python3.13/tomllib/__init__.py +10 -0
  471. package/python/lib/python3.13/tomllib/_parser.py +703 -0
  472. package/python/lib/python3.13/tomllib/_re.py +107 -0
  473. package/python/lib/python3.13/tomllib/_types.py +10 -0
  474. package/python/lib/python3.13/tomllib/mypy.ini +15 -0
  475. package/python/lib/python3.13/trace.py +754 -0
  476. package/python/lib/python3.13/traceback.py +1639 -0
  477. package/python/lib/python3.13/tracemalloc.py +560 -0
  478. package/python/lib/python3.13/tty.py +73 -0
  479. package/python/lib/python3.13/types.py +346 -0
  480. package/python/lib/python3.13/typing.py +3846 -0
  481. package/python/lib/python3.13/unittest/__init__.py +80 -0
  482. package/python/lib/python3.13/unittest/__main__.py +18 -0
  483. package/python/lib/python3.13/unittest/_log.py +86 -0
  484. package/python/lib/python3.13/unittest/async_case.py +146 -0
  485. package/python/lib/python3.13/unittest/case.py +1478 -0
  486. package/python/lib/python3.13/unittest/loader.py +460 -0
  487. package/python/lib/python3.13/unittest/main.py +280 -0
  488. package/python/lib/python3.13/unittest/mock.py +3189 -0
  489. package/python/lib/python3.13/unittest/result.py +256 -0
  490. package/python/lib/python3.13/unittest/runner.py +292 -0
  491. package/python/lib/python3.13/unittest/signals.py +71 -0
  492. package/python/lib/python3.13/unittest/suite.py +379 -0
  493. package/python/lib/python3.13/unittest/util.py +170 -0
  494. package/python/lib/python3.13/urllib/__init__.py +0 -0
  495. package/python/lib/python3.13/urllib/error.py +74 -0
  496. package/python/lib/python3.13/urllib/parse.py +1264 -0
  497. package/python/lib/python3.13/urllib/request.py +2796 -0
  498. package/python/lib/python3.13/urllib/response.py +84 -0
  499. package/python/lib/python3.13/urllib/robotparser.py +363 -0
  500. package/python/lib/python3.13/uuid.py +784 -0
  501. package/python/lib/python3.13/warnings.py +735 -0
  502. package/python/lib/python3.13/wave.py +665 -0
  503. package/python/lib/python3.13/weakref.py +674 -0
  504. package/python/lib/python3.13/webbrowser.py +724 -0
  505. package/python/lib/python3.13/wsgiref/__init__.py +25 -0
  506. package/python/lib/python3.13/wsgiref/handlers.py +575 -0
  507. package/python/lib/python3.13/wsgiref/headers.py +192 -0
  508. package/python/lib/python3.13/wsgiref/simple_server.py +161 -0
  509. package/python/lib/python3.13/wsgiref/types.py +54 -0
  510. package/python/lib/python3.13/wsgiref/util.py +159 -0
  511. package/python/lib/python3.13/wsgiref/validate.py +438 -0
  512. package/python/lib/python3.13/xml/__init__.py +20 -0
  513. package/python/lib/python3.13/xml/dom/NodeFilter.py +27 -0
  514. package/python/lib/python3.13/xml/dom/__init__.py +140 -0
  515. package/python/lib/python3.13/xml/dom/domreg.py +99 -0
  516. package/python/lib/python3.13/xml/dom/expatbuilder.py +962 -0
  517. package/python/lib/python3.13/xml/dom/minicompat.py +109 -0
  518. package/python/lib/python3.13/xml/dom/minidom.py +2024 -0
  519. package/python/lib/python3.13/xml/dom/pulldom.py +336 -0
  520. package/python/lib/python3.13/xml/dom/xmlbuilder.py +389 -0
  521. package/python/lib/python3.13/xml/etree/ElementInclude.py +186 -0
  522. package/python/lib/python3.13/xml/etree/ElementPath.py +430 -0
  523. package/python/lib/python3.13/xml/etree/ElementTree.py +2116 -0
  524. package/python/lib/python3.13/xml/etree/__init__.py +33 -0
  525. package/python/lib/python3.13/xml/etree/cElementTree.py +3 -0
  526. package/python/lib/python3.13/xml/parsers/__init__.py +8 -0
  527. package/python/lib/python3.13/xml/parsers/expat.py +8 -0
  528. package/python/lib/python3.13/xml/sax/__init__.py +94 -0
  529. package/python/lib/python3.13/xml/sax/_exceptions.py +127 -0
  530. package/python/lib/python3.13/xml/sax/expatreader.py +454 -0
  531. package/python/lib/python3.13/xml/sax/handler.py +387 -0
  532. package/python/lib/python3.13/xml/sax/saxutils.py +369 -0
  533. package/python/lib/python3.13/xml/sax/xmlreader.py +378 -0
  534. package/python/lib/python3.13/xmlrpc/__init__.py +1 -0
  535. package/python/lib/python3.13/xmlrpc/client.py +1503 -0
  536. package/python/lib/python3.13/xmlrpc/server.py +1002 -0
  537. package/python/lib/python3.13/zipapp.py +229 -0
  538. package/python/lib/python3.13/zipfile/__init__.py +2391 -0
  539. package/python/lib/python3.13/zipfile/__main__.py +4 -0
  540. package/python/lib/python3.13/zipfile/_path/__init__.py +452 -0
  541. package/python/lib/python3.13/zipfile/_path/glob.py +113 -0
  542. package/python/lib/python3.13/zipimport.py +803 -0
  543. package/python/lib/python3.13/zoneinfo/__init__.py +34 -0
  544. package/python/lib/python3.13/zoneinfo/_common.py +172 -0
  545. package/python/lib/python3.13/zoneinfo/_tzpath.py +189 -0
  546. package/python/lib/python3.13/zoneinfo/_zoneinfo.py +779 -0
  547. package/python/licenses/LICENSE.bdb.txt +126 -0
  548. package/python/licenses/LICENSE.bzip2.txt +37 -0
  549. package/python/licenses/LICENSE.cpython.txt +771 -0
  550. package/python/licenses/LICENSE.expat.txt +21 -0
  551. package/python/licenses/LICENSE.libX11.txt +942 -0
  552. package/python/licenses/LICENSE.libXau.txt +21 -0
  553. package/python/licenses/LICENSE.libedit.txt +29 -0
  554. package/python/licenses/LICENSE.libffi.txt +21 -0
  555. package/python/licenses/LICENSE.liblzma.txt +13 -0
  556. package/python/licenses/LICENSE.libuuid.txt +27 -0
  557. package/python/licenses/LICENSE.libxcb.txt +30 -0
  558. package/python/licenses/LICENSE.mpdecimal.txt +24 -0
  559. package/python/licenses/LICENSE.ncurses.txt +29 -0
  560. package/python/licenses/LICENSE.openssl-1.1.txt +124 -0
  561. package/python/licenses/LICENSE.openssl-3.txt +177 -0
  562. package/python/licenses/LICENSE.sqlite.txt +23 -0
  563. package/python/licenses/LICENSE.tcl.txt +40 -0
  564. package/python/licenses/LICENSE.tix.txt +54 -0
  565. package/python/licenses/LICENSE.zlib.txt +21 -0
@@ -0,0 +1,1639 @@
1
+ """Extract, format and print information about Python stack traces."""
2
+
3
+ import collections.abc
4
+ import itertools
5
+ import linecache
6
+ import sys
7
+ import textwrap
8
+ import warnings
9
+ from contextlib import suppress
10
+ import _colorize
11
+ from _colorize import ANSIColors
12
+
13
+ __all__ = ['extract_stack', 'extract_tb', 'format_exception',
14
+ 'format_exception_only', 'format_list', 'format_stack',
15
+ 'format_tb', 'print_exc', 'format_exc', 'print_exception',
16
+ 'print_last', 'print_stack', 'print_tb', 'clear_frames',
17
+ 'FrameSummary', 'StackSummary', 'TracebackException',
18
+ 'walk_stack', 'walk_tb']
19
+
20
+ #
21
+ # Formatting and printing lists of traceback lines.
22
+ #
23
+
24
+
25
+ def print_list(extracted_list, file=None):
26
+ """Print the list of tuples as returned by extract_tb() or
27
+ extract_stack() as a formatted stack trace to the given file."""
28
+ if file is None:
29
+ file = sys.stderr
30
+ for item in StackSummary.from_list(extracted_list).format():
31
+ print(item, file=file, end="")
32
+
33
+ def format_list(extracted_list):
34
+ """Format a list of tuples or FrameSummary objects for printing.
35
+
36
+ Given a list of tuples or FrameSummary objects as returned by
37
+ extract_tb() or extract_stack(), return a list of strings ready
38
+ for printing.
39
+
40
+ Each string in the resulting list corresponds to the item with the
41
+ same index in the argument list. Each string ends in a newline;
42
+ the strings may contain internal newlines as well, for those items
43
+ whose source text line is not None.
44
+ """
45
+ return StackSummary.from_list(extracted_list).format()
46
+
47
+ #
48
+ # Printing and Extracting Tracebacks.
49
+ #
50
+
51
+ def print_tb(tb, limit=None, file=None):
52
+ """Print up to 'limit' stack trace entries from the traceback 'tb'.
53
+
54
+ If 'limit' is omitted or None, all entries are printed. If 'file'
55
+ is omitted or None, the output goes to sys.stderr; otherwise
56
+ 'file' should be an open file or file-like object with a write()
57
+ method.
58
+ """
59
+ print_list(extract_tb(tb, limit=limit), file=file)
60
+
61
+ def format_tb(tb, limit=None):
62
+ """A shorthand for 'format_list(extract_tb(tb, limit))'."""
63
+ return extract_tb(tb, limit=limit).format()
64
+
65
+ def extract_tb(tb, limit=None):
66
+ """
67
+ Return a StackSummary object representing a list of
68
+ pre-processed entries from traceback.
69
+
70
+ This is useful for alternate formatting of stack traces. If
71
+ 'limit' is omitted or None, all entries are extracted. A
72
+ pre-processed stack trace entry is a FrameSummary object
73
+ representing the information that is usually printed for a
74
+ stack trace. The line attribute is a string with
75
+ leading and trailing whitespace stripped; if the source is not
76
+ available the corresponding attribute is None.
77
+ """
78
+ return StackSummary._extract_from_extended_frame_gen(
79
+ _walk_tb_with_full_positions(tb), limit=limit)
80
+
81
+ #
82
+ # Exception formatting and output.
83
+ #
84
+
85
+ _cause_message = (
86
+ "\nThe above exception was the direct cause "
87
+ "of the following exception:\n\n")
88
+
89
+ _context_message = (
90
+ "\nDuring handling of the above exception, "
91
+ "another exception occurred:\n\n")
92
+
93
+
94
+ class _Sentinel:
95
+ def __repr__(self):
96
+ return "<implicit>"
97
+
98
+ _sentinel = _Sentinel()
99
+
100
+ def _parse_value_tb(exc, value, tb):
101
+ if (value is _sentinel) != (tb is _sentinel):
102
+ raise ValueError("Both or neither of value and tb must be given")
103
+ if value is tb is _sentinel:
104
+ if exc is not None:
105
+ if isinstance(exc, BaseException):
106
+ return exc, exc.__traceback__
107
+
108
+ raise TypeError(f'Exception expected for value, '
109
+ f'{type(exc).__name__} found')
110
+ else:
111
+ return None, None
112
+ return value, tb
113
+
114
+
115
+ def print_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \
116
+ file=None, chain=True, **kwargs):
117
+ """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
118
+
119
+ This differs from print_tb() in the following ways: (1) if
120
+ traceback is not None, it prints a header "Traceback (most recent
121
+ call last):"; (2) it prints the exception type and value after the
122
+ stack trace; (3) if type is SyntaxError and value has the
123
+ appropriate format, it prints the line where the syntax error
124
+ occurred with a caret on the next line indicating the approximate
125
+ position of the error.
126
+ """
127
+ colorize = kwargs.get("colorize", False)
128
+ value, tb = _parse_value_tb(exc, value, tb)
129
+ te = TracebackException(type(value), value, tb, limit=limit, compact=True)
130
+ te.print(file=file, chain=chain, colorize=colorize)
131
+
132
+
133
+ BUILTIN_EXCEPTION_LIMIT = object()
134
+
135
+
136
+ def _print_exception_bltin(exc, /):
137
+ file = sys.stderr if sys.stderr is not None else sys.__stderr__
138
+ colorize = _colorize.can_colorize(file=file)
139
+ return print_exception(exc, limit=BUILTIN_EXCEPTION_LIMIT, file=file, colorize=colorize)
140
+
141
+
142
+ def format_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \
143
+ chain=True, **kwargs):
144
+ """Format a stack trace and the exception information.
145
+
146
+ The arguments have the same meaning as the corresponding arguments
147
+ to print_exception(). The return value is a list of strings, each
148
+ ending in a newline and some containing internal newlines. When
149
+ these lines are concatenated and printed, exactly the same text is
150
+ printed as does print_exception().
151
+ """
152
+ colorize = kwargs.get("colorize", False)
153
+ value, tb = _parse_value_tb(exc, value, tb)
154
+ te = TracebackException(type(value), value, tb, limit=limit, compact=True)
155
+ return list(te.format(chain=chain, colorize=colorize))
156
+
157
+
158
+ def format_exception_only(exc, /, value=_sentinel, *, show_group=False, **kwargs):
159
+ """Format the exception part of a traceback.
160
+
161
+ The return value is a list of strings, each ending in a newline.
162
+
163
+ The list contains the exception's message, which is
164
+ normally a single string; however, for :exc:`SyntaxError` exceptions, it
165
+ contains several lines that (when printed) display detailed information
166
+ about where the syntax error occurred. Following the message, the list
167
+ contains the exception's ``__notes__``.
168
+
169
+ When *show_group* is ``True``, and the exception is an instance of
170
+ :exc:`BaseExceptionGroup`, the nested exceptions are included as
171
+ well, recursively, with indentation relative to their nesting depth.
172
+ """
173
+ colorize = kwargs.get("colorize", False)
174
+ if value is _sentinel:
175
+ value = exc
176
+ te = TracebackException(type(value), value, None, compact=True)
177
+ return list(te.format_exception_only(show_group=show_group, colorize=colorize))
178
+
179
+
180
+ # -- not official API but folk probably use these two functions.
181
+
182
+ def _format_final_exc_line(etype, value, *, insert_final_newline=True, colorize=False):
183
+ valuestr = _safe_string(value, 'exception')
184
+ end_char = "\n" if insert_final_newline else ""
185
+ if colorize:
186
+ if value is None or not valuestr:
187
+ line = f"{ANSIColors.BOLD_MAGENTA}{etype}{ANSIColors.RESET}{end_char}"
188
+ else:
189
+ line = f"{ANSIColors.BOLD_MAGENTA}{etype}{ANSIColors.RESET}: {ANSIColors.MAGENTA}{valuestr}{ANSIColors.RESET}{end_char}"
190
+ else:
191
+ if value is None or not valuestr:
192
+ line = f"{etype}{end_char}"
193
+ else:
194
+ line = f"{etype}: {valuestr}{end_char}"
195
+ return line
196
+
197
+
198
+ def _safe_string(value, what, func=str):
199
+ try:
200
+ return func(value)
201
+ except:
202
+ return f'<{what} {func.__name__}() failed>'
203
+
204
+ # --
205
+
206
+ def print_exc(limit=None, file=None, chain=True):
207
+ """Shorthand for 'print_exception(sys.exception(), limit=limit, file=file, chain=chain)'."""
208
+ print_exception(sys.exception(), limit=limit, file=file, chain=chain)
209
+
210
+ def format_exc(limit=None, chain=True):
211
+ """Like print_exc() but return a string."""
212
+ return "".join(format_exception(sys.exception(), limit=limit, chain=chain))
213
+
214
+ def print_last(limit=None, file=None, chain=True):
215
+ """This is a shorthand for 'print_exception(sys.last_exc, limit=limit, file=file, chain=chain)'."""
216
+ if not hasattr(sys, "last_exc") and not hasattr(sys, "last_type"):
217
+ raise ValueError("no last exception")
218
+
219
+ if hasattr(sys, "last_exc"):
220
+ print_exception(sys.last_exc, limit=limit, file=file, chain=chain)
221
+ else:
222
+ print_exception(sys.last_type, sys.last_value, sys.last_traceback,
223
+ limit=limit, file=file, chain=chain)
224
+
225
+
226
+ #
227
+ # Printing and Extracting Stacks.
228
+ #
229
+
230
+ def print_stack(f=None, limit=None, file=None):
231
+ """Print a stack trace from its invocation point.
232
+
233
+ The optional 'f' argument can be used to specify an alternate
234
+ stack frame at which to start. The optional 'limit' and 'file'
235
+ arguments have the same meaning as for print_exception().
236
+ """
237
+ if f is None:
238
+ f = sys._getframe().f_back
239
+ print_list(extract_stack(f, limit=limit), file=file)
240
+
241
+
242
+ def format_stack(f=None, limit=None):
243
+ """Shorthand for 'format_list(extract_stack(f, limit))'."""
244
+ if f is None:
245
+ f = sys._getframe().f_back
246
+ return format_list(extract_stack(f, limit=limit))
247
+
248
+
249
+ def extract_stack(f=None, limit=None):
250
+ """Extract the raw traceback from the current stack frame.
251
+
252
+ The return value has the same format as for extract_tb(). The
253
+ optional 'f' and 'limit' arguments have the same meaning as for
254
+ print_stack(). Each item in the list is a FrameSummary object,
255
+ and the entries are in order from oldest to newest stack frame.
256
+ """
257
+ if f is None:
258
+ f = sys._getframe().f_back
259
+ stack = StackSummary.extract(walk_stack(f), limit=limit)
260
+ stack.reverse()
261
+ return stack
262
+
263
+
264
+ def clear_frames(tb):
265
+ "Clear all references to local variables in the frames of a traceback."
266
+ while tb is not None:
267
+ try:
268
+ tb.tb_frame.clear()
269
+ except RuntimeError:
270
+ # Ignore the exception raised if the frame is still executing.
271
+ pass
272
+ tb = tb.tb_next
273
+
274
+
275
+ class FrameSummary:
276
+ """Information about a single frame from a traceback.
277
+
278
+ - :attr:`filename` The filename for the frame.
279
+ - :attr:`lineno` The line within filename for the frame that was
280
+ active when the frame was captured.
281
+ - :attr:`name` The name of the function or method that was executing
282
+ when the frame was captured.
283
+ - :attr:`line` The text from the linecache module for the line
284
+ of code that was running when the frame was captured.
285
+ - :attr:`locals` Either None if locals were not supplied, or a dict
286
+ mapping the name to the repr() of the variable.
287
+ """
288
+
289
+ __slots__ = ('filename', 'lineno', 'end_lineno', 'colno', 'end_colno',
290
+ 'name', '_lines', '_lines_dedented', 'locals', '_code')
291
+
292
+ def __init__(self, filename, lineno, name, *, lookup_line=True,
293
+ locals=None, line=None,
294
+ end_lineno=None, colno=None, end_colno=None, **kwargs):
295
+ """Construct a FrameSummary.
296
+
297
+ :param lookup_line: If True, `linecache` is consulted for the source
298
+ code line. Otherwise, the line will be looked up when first needed.
299
+ :param locals: If supplied the frame locals, which will be captured as
300
+ object representations.
301
+ :param line: If provided, use this instead of looking up the line in
302
+ the linecache.
303
+ """
304
+ self.filename = filename
305
+ self.lineno = lineno
306
+ self.end_lineno = lineno if end_lineno is None else end_lineno
307
+ self.colno = colno
308
+ self.end_colno = end_colno
309
+ self.name = name
310
+ self._code = kwargs.get("_code")
311
+ self._lines = line
312
+ self._lines_dedented = None
313
+ if lookup_line:
314
+ self.line
315
+ self.locals = {k: _safe_string(v, 'local', func=repr)
316
+ for k, v in locals.items()} if locals else None
317
+
318
+ def __eq__(self, other):
319
+ if isinstance(other, FrameSummary):
320
+ return (self.filename == other.filename and
321
+ self.lineno == other.lineno and
322
+ self.name == other.name and
323
+ self.locals == other.locals)
324
+ if isinstance(other, tuple):
325
+ return (self.filename, self.lineno, self.name, self.line) == other
326
+ return NotImplemented
327
+
328
+ def __getitem__(self, pos):
329
+ return (self.filename, self.lineno, self.name, self.line)[pos]
330
+
331
+ def __iter__(self):
332
+ return iter([self.filename, self.lineno, self.name, self.line])
333
+
334
+ def __repr__(self):
335
+ return "<FrameSummary file {filename}, line {lineno} in {name}>".format(
336
+ filename=self.filename, lineno=self.lineno, name=self.name)
337
+
338
+ def __len__(self):
339
+ return 4
340
+
341
+ def _set_lines(self):
342
+ if (
343
+ self._lines is None
344
+ and self.lineno is not None
345
+ and self.end_lineno is not None
346
+ ):
347
+ lines = []
348
+ for lineno in range(self.lineno, self.end_lineno + 1):
349
+ # treat errors (empty string) and empty lines (newline) as the same
350
+ line = linecache.getline(self.filename, lineno).rstrip()
351
+ if not line and self._code is not None and self.filename.startswith("<"):
352
+ line = linecache._getline_from_code(self._code, lineno).rstrip()
353
+ lines.append(line)
354
+ self._lines = "\n".join(lines) + "\n"
355
+
356
+ @property
357
+ def _original_lines(self):
358
+ # Returns the line as-is from the source, without modifying whitespace.
359
+ self._set_lines()
360
+ return self._lines
361
+
362
+ @property
363
+ def _dedented_lines(self):
364
+ # Returns _original_lines, but dedented
365
+ self._set_lines()
366
+ if self._lines_dedented is None and self._lines is not None:
367
+ self._lines_dedented = textwrap.dedent(self._lines)
368
+ return self._lines_dedented
369
+
370
+ @property
371
+ def line(self):
372
+ self._set_lines()
373
+ if self._lines is None:
374
+ return None
375
+ # return only the first line, stripped
376
+ return self._lines.partition("\n")[0].strip()
377
+
378
+
379
+ def walk_stack(f):
380
+ """Walk a stack yielding the frame and line number for each frame.
381
+
382
+ This will follow f.f_back from the given frame. If no frame is given, the
383
+ current stack is used. Usually used with StackSummary.extract.
384
+ """
385
+ if f is None:
386
+ f = sys._getframe().f_back.f_back.f_back.f_back
387
+ while f is not None:
388
+ yield f, f.f_lineno
389
+ f = f.f_back
390
+
391
+
392
+ def walk_tb(tb):
393
+ """Walk a traceback yielding the frame and line number for each frame.
394
+
395
+ This will follow tb.tb_next (and thus is in the opposite order to
396
+ walk_stack). Usually used with StackSummary.extract.
397
+ """
398
+ while tb is not None:
399
+ yield tb.tb_frame, tb.tb_lineno
400
+ tb = tb.tb_next
401
+
402
+
403
+ def _walk_tb_with_full_positions(tb):
404
+ # Internal version of walk_tb that yields full code positions including
405
+ # end line and column information.
406
+ while tb is not None:
407
+ positions = _get_code_position(tb.tb_frame.f_code, tb.tb_lasti)
408
+ # Yield tb_lineno when co_positions does not have a line number to
409
+ # maintain behavior with walk_tb.
410
+ if positions[0] is None:
411
+ yield tb.tb_frame, (tb.tb_lineno, ) + positions[1:]
412
+ else:
413
+ yield tb.tb_frame, positions
414
+ tb = tb.tb_next
415
+
416
+
417
+ def _get_code_position(code, instruction_index):
418
+ if instruction_index < 0:
419
+ return (None, None, None, None)
420
+ positions_gen = code.co_positions()
421
+ return next(itertools.islice(positions_gen, instruction_index // 2, None))
422
+
423
+
424
+ _RECURSIVE_CUTOFF = 3 # Also hardcoded in traceback.c.
425
+
426
+
427
+ class StackSummary(list):
428
+ """A list of FrameSummary objects, representing a stack of frames."""
429
+
430
+ @classmethod
431
+ def extract(klass, frame_gen, *, limit=None, lookup_lines=True,
432
+ capture_locals=False):
433
+ """Create a StackSummary from a traceback or stack object.
434
+
435
+ :param frame_gen: A generator that yields (frame, lineno) tuples
436
+ whose summaries are to be included in the stack.
437
+ :param limit: None to include all frames or the number of frames to
438
+ include.
439
+ :param lookup_lines: If True, lookup lines for each frame immediately,
440
+ otherwise lookup is deferred until the frame is rendered.
441
+ :param capture_locals: If True, the local variables from each frame will
442
+ be captured as object representations into the FrameSummary.
443
+ """
444
+ def extended_frame_gen():
445
+ for f, lineno in frame_gen:
446
+ yield f, (lineno, None, None, None)
447
+
448
+ return klass._extract_from_extended_frame_gen(
449
+ extended_frame_gen(), limit=limit, lookup_lines=lookup_lines,
450
+ capture_locals=capture_locals)
451
+
452
+ @classmethod
453
+ def _extract_from_extended_frame_gen(klass, frame_gen, *, limit=None,
454
+ lookup_lines=True, capture_locals=False):
455
+ # Same as extract but operates on a frame generator that yields
456
+ # (frame, (lineno, end_lineno, colno, end_colno)) in the stack.
457
+ # Only lineno is required, the remaining fields can be None if the
458
+ # information is not available.
459
+ builtin_limit = limit is BUILTIN_EXCEPTION_LIMIT
460
+ if limit is None or builtin_limit:
461
+ limit = getattr(sys, 'tracebacklimit', None)
462
+ if limit is not None and limit < 0:
463
+ limit = 0
464
+ if limit is not None:
465
+ if builtin_limit:
466
+ frame_gen = tuple(frame_gen)
467
+ frame_gen = frame_gen[len(frame_gen) - limit:]
468
+ elif limit >= 0:
469
+ frame_gen = itertools.islice(frame_gen, limit)
470
+ else:
471
+ frame_gen = collections.deque(frame_gen, maxlen=-limit)
472
+
473
+ result = klass()
474
+ fnames = set()
475
+ for f, (lineno, end_lineno, colno, end_colno) in frame_gen:
476
+ co = f.f_code
477
+ filename = co.co_filename
478
+ name = co.co_name
479
+ fnames.add(filename)
480
+ linecache.lazycache(filename, f.f_globals)
481
+ # Must defer line lookups until we have called checkcache.
482
+ if capture_locals:
483
+ f_locals = f.f_locals
484
+ else:
485
+ f_locals = None
486
+ result.append(
487
+ FrameSummary(filename, lineno, name,
488
+ lookup_line=False, locals=f_locals,
489
+ end_lineno=end_lineno, colno=colno, end_colno=end_colno,
490
+ _code=f.f_code,
491
+ )
492
+ )
493
+ for filename in fnames:
494
+ linecache.checkcache(filename)
495
+
496
+ # If immediate lookup was desired, trigger lookups now.
497
+ if lookup_lines:
498
+ for f in result:
499
+ f.line
500
+ return result
501
+
502
+ @classmethod
503
+ def from_list(klass, a_list):
504
+ """
505
+ Create a StackSummary object from a supplied list of
506
+ FrameSummary objects or old-style list of tuples.
507
+ """
508
+ # While doing a fast-path check for isinstance(a_list, StackSummary) is
509
+ # appealing, idlelib.run.cleanup_traceback and other similar code may
510
+ # break this by making arbitrary frames plain tuples, so we need to
511
+ # check on a frame by frame basis.
512
+ result = StackSummary()
513
+ for frame in a_list:
514
+ if isinstance(frame, FrameSummary):
515
+ result.append(frame)
516
+ else:
517
+ filename, lineno, name, line = frame
518
+ result.append(FrameSummary(filename, lineno, name, line=line))
519
+ return result
520
+
521
+ def format_frame_summary(self, frame_summary, **kwargs):
522
+ """Format the lines for a single FrameSummary.
523
+
524
+ Returns a string representing one frame involved in the stack. This
525
+ gets called for every frame to be printed in the stack summary.
526
+ """
527
+ colorize = kwargs.get("colorize", False)
528
+ row = []
529
+ filename = frame_summary.filename
530
+ if frame_summary.filename.startswith("<stdin-") and frame_summary.filename.endswith('>'):
531
+ filename = "<stdin>"
532
+ if colorize:
533
+ row.append(' File {}"{}"{}, line {}{}{}, in {}{}{}\n'.format(
534
+ ANSIColors.MAGENTA,
535
+ filename,
536
+ ANSIColors.RESET,
537
+ ANSIColors.MAGENTA,
538
+ frame_summary.lineno,
539
+ ANSIColors.RESET,
540
+ ANSIColors.MAGENTA,
541
+ frame_summary.name,
542
+ ANSIColors.RESET,
543
+ )
544
+ )
545
+ else:
546
+ row.append(' File "{}", line {}, in {}\n'.format(
547
+ filename, frame_summary.lineno, frame_summary.name))
548
+ if frame_summary._dedented_lines and frame_summary._dedented_lines.strip():
549
+ if (
550
+ frame_summary.colno is None or
551
+ frame_summary.end_colno is None
552
+ ):
553
+ # only output first line if column information is missing
554
+ row.append(textwrap.indent(frame_summary.line, ' ') + "\n")
555
+ else:
556
+ # get first and last line
557
+ all_lines_original = frame_summary._original_lines.splitlines()
558
+ first_line = all_lines_original[0]
559
+ # assume all_lines_original has enough lines (since we constructed it)
560
+ last_line = all_lines_original[frame_summary.end_lineno - frame_summary.lineno]
561
+
562
+ # character index of the start/end of the instruction
563
+ start_offset = _byte_offset_to_character_offset(first_line, frame_summary.colno)
564
+ end_offset = _byte_offset_to_character_offset(last_line, frame_summary.end_colno)
565
+
566
+ all_lines = frame_summary._dedented_lines.splitlines()[
567
+ :frame_summary.end_lineno - frame_summary.lineno + 1
568
+ ]
569
+
570
+ # adjust start/end offset based on dedent
571
+ dedent_characters = len(first_line) - len(all_lines[0])
572
+ start_offset = max(0, start_offset - dedent_characters)
573
+ end_offset = max(0, end_offset - dedent_characters)
574
+
575
+ # When showing this on a terminal, some of the non-ASCII characters
576
+ # might be rendered as double-width characters, so we need to take
577
+ # that into account when calculating the length of the line.
578
+ dp_start_offset = _display_width(all_lines[0], offset=start_offset)
579
+ dp_end_offset = _display_width(all_lines[-1], offset=end_offset)
580
+
581
+ # get exact code segment corresponding to the instruction
582
+ segment = "\n".join(all_lines)
583
+ segment = segment[start_offset:len(segment) - (len(all_lines[-1]) - end_offset)]
584
+
585
+ # attempt to parse for anchors
586
+ anchors = None
587
+ show_carets = False
588
+ with suppress(Exception):
589
+ anchors = _extract_caret_anchors_from_line_segment(segment)
590
+ show_carets = self._should_show_carets(start_offset, end_offset, all_lines, anchors)
591
+
592
+ result = []
593
+
594
+ # only display first line, last line, and lines around anchor start/end
595
+ significant_lines = {0, len(all_lines) - 1}
596
+
597
+ anchors_left_end_offset = 0
598
+ anchors_right_start_offset = 0
599
+ primary_char = "^"
600
+ secondary_char = "^"
601
+ if anchors:
602
+ anchors_left_end_offset = anchors.left_end_offset
603
+ anchors_right_start_offset = anchors.right_start_offset
604
+ # computed anchor positions do not take start_offset into account,
605
+ # so account for it here
606
+ if anchors.left_end_lineno == 0:
607
+ anchors_left_end_offset += start_offset
608
+ if anchors.right_start_lineno == 0:
609
+ anchors_right_start_offset += start_offset
610
+
611
+ # account for display width
612
+ anchors_left_end_offset = _display_width(
613
+ all_lines[anchors.left_end_lineno], offset=anchors_left_end_offset
614
+ )
615
+ anchors_right_start_offset = _display_width(
616
+ all_lines[anchors.right_start_lineno], offset=anchors_right_start_offset
617
+ )
618
+
619
+ primary_char = anchors.primary_char
620
+ secondary_char = anchors.secondary_char
621
+ significant_lines.update(
622
+ range(anchors.left_end_lineno - 1, anchors.left_end_lineno + 2)
623
+ )
624
+ significant_lines.update(
625
+ range(anchors.right_start_lineno - 1, anchors.right_start_lineno + 2)
626
+ )
627
+
628
+ # remove bad line numbers
629
+ significant_lines.discard(-1)
630
+ significant_lines.discard(len(all_lines))
631
+
632
+ def output_line(lineno):
633
+ """output all_lines[lineno] along with carets"""
634
+ result.append(all_lines[lineno] + "\n")
635
+ if not show_carets:
636
+ return
637
+ num_spaces = len(all_lines[lineno]) - len(all_lines[lineno].lstrip())
638
+ carets = []
639
+ num_carets = dp_end_offset if lineno == len(all_lines) - 1 else _display_width(all_lines[lineno])
640
+ # compute caret character for each position
641
+ for col in range(num_carets):
642
+ if col < num_spaces or (lineno == 0 and col < dp_start_offset):
643
+ # before first non-ws char of the line, or before start of instruction
644
+ carets.append(' ')
645
+ elif anchors and (
646
+ lineno > anchors.left_end_lineno or
647
+ (lineno == anchors.left_end_lineno and col >= anchors_left_end_offset)
648
+ ) and (
649
+ lineno < anchors.right_start_lineno or
650
+ (lineno == anchors.right_start_lineno and col < anchors_right_start_offset)
651
+ ):
652
+ # within anchors
653
+ carets.append(secondary_char)
654
+ else:
655
+ carets.append(primary_char)
656
+ if colorize:
657
+ # Replace the previous line with a red version of it only in the parts covered
658
+ # by the carets.
659
+ line = result[-1]
660
+ colorized_line_parts = []
661
+ colorized_carets_parts = []
662
+
663
+ for color, group in itertools.groupby(itertools.zip_longest(line, carets, fillvalue=""), key=lambda x: x[1]):
664
+ caret_group = list(group)
665
+ if color == "^":
666
+ colorized_line_parts.append(ANSIColors.BOLD_RED + "".join(char for char, _ in caret_group) + ANSIColors.RESET)
667
+ colorized_carets_parts.append(ANSIColors.BOLD_RED + "".join(caret for _, caret in caret_group) + ANSIColors.RESET)
668
+ elif color == "~":
669
+ colorized_line_parts.append(ANSIColors.RED + "".join(char for char, _ in caret_group) + ANSIColors.RESET)
670
+ colorized_carets_parts.append(ANSIColors.RED + "".join(caret for _, caret in caret_group) + ANSIColors.RESET)
671
+ else:
672
+ colorized_line_parts.append("".join(char for char, _ in caret_group))
673
+ colorized_carets_parts.append("".join(caret for _, caret in caret_group))
674
+
675
+ colorized_line = "".join(colorized_line_parts)
676
+ colorized_carets = "".join(colorized_carets_parts)
677
+ result[-1] = colorized_line
678
+ result.append(colorized_carets + "\n")
679
+ else:
680
+ result.append("".join(carets) + "\n")
681
+
682
+ # display significant lines
683
+ sig_lines_list = sorted(significant_lines)
684
+ for i, lineno in enumerate(sig_lines_list):
685
+ if i:
686
+ linediff = lineno - sig_lines_list[i - 1]
687
+ if linediff == 2:
688
+ # 1 line in between - just output it
689
+ output_line(lineno - 1)
690
+ elif linediff > 2:
691
+ # > 1 line in between - abbreviate
692
+ result.append(f"...<{linediff - 1} lines>...\n")
693
+ output_line(lineno)
694
+
695
+ row.append(
696
+ textwrap.indent(textwrap.dedent("".join(result)), ' ', lambda line: True)
697
+ )
698
+ if frame_summary.locals:
699
+ for name, value in sorted(frame_summary.locals.items()):
700
+ row.append(' {name} = {value}\n'.format(name=name, value=value))
701
+
702
+ return ''.join(row)
703
+
704
+ def _should_show_carets(self, start_offset, end_offset, all_lines, anchors):
705
+ with suppress(SyntaxError, ImportError):
706
+ import ast
707
+ tree = ast.parse('\n'.join(all_lines))
708
+ if not tree.body:
709
+ return False
710
+ statement = tree.body[0]
711
+ value = None
712
+ def _spawns_full_line(value):
713
+ return (
714
+ value.lineno == 1
715
+ and value.end_lineno == len(all_lines)
716
+ and value.col_offset == start_offset
717
+ and value.end_col_offset == end_offset
718
+ )
719
+ match statement:
720
+ case ast.Return(value=ast.Call()):
721
+ if isinstance(statement.value.func, ast.Name):
722
+ value = statement.value
723
+ case ast.Assign(value=ast.Call()):
724
+ if (
725
+ len(statement.targets) == 1 and
726
+ isinstance(statement.targets[0], ast.Name)
727
+ ):
728
+ value = statement.value
729
+ if value is not None and _spawns_full_line(value):
730
+ return False
731
+ if anchors:
732
+ return True
733
+ if all_lines[0][:start_offset].lstrip() or all_lines[-1][end_offset:].rstrip():
734
+ return True
735
+ return False
736
+
737
+ def format(self, **kwargs):
738
+ """Format the stack ready for printing.
739
+
740
+ Returns a list of strings ready for printing. Each string in the
741
+ resulting list corresponds to a single frame from the stack.
742
+ Each string ends in a newline; the strings may contain internal
743
+ newlines as well, for those items with source text lines.
744
+
745
+ For long sequences of the same frame and line, the first few
746
+ repetitions are shown, followed by a summary line stating the exact
747
+ number of further repetitions.
748
+ """
749
+ colorize = kwargs.get("colorize", False)
750
+ result = []
751
+ last_file = None
752
+ last_line = None
753
+ last_name = None
754
+ count = 0
755
+ for frame_summary in self:
756
+ formatted_frame = self.format_frame_summary(frame_summary, colorize=colorize)
757
+ if formatted_frame is None:
758
+ continue
759
+ if (last_file is None or last_file != frame_summary.filename or
760
+ last_line is None or last_line != frame_summary.lineno or
761
+ last_name is None or last_name != frame_summary.name):
762
+ if count > _RECURSIVE_CUTOFF:
763
+ count -= _RECURSIVE_CUTOFF
764
+ result.append(
765
+ f' [Previous line repeated {count} more '
766
+ f'time{"s" if count > 1 else ""}]\n'
767
+ )
768
+ last_file = frame_summary.filename
769
+ last_line = frame_summary.lineno
770
+ last_name = frame_summary.name
771
+ count = 0
772
+ count += 1
773
+ if count > _RECURSIVE_CUTOFF:
774
+ continue
775
+ result.append(formatted_frame)
776
+
777
+ if count > _RECURSIVE_CUTOFF:
778
+ count -= _RECURSIVE_CUTOFF
779
+ result.append(
780
+ f' [Previous line repeated {count} more '
781
+ f'time{"s" if count > 1 else ""}]\n'
782
+ )
783
+ return result
784
+
785
+
786
+ def _byte_offset_to_character_offset(str, offset):
787
+ as_utf8 = str.encode('utf-8')
788
+ return len(as_utf8[:offset].decode("utf-8", errors="replace"))
789
+
790
+
791
+ _Anchors = collections.namedtuple(
792
+ "_Anchors",
793
+ [
794
+ "left_end_lineno",
795
+ "left_end_offset",
796
+ "right_start_lineno",
797
+ "right_start_offset",
798
+ "primary_char",
799
+ "secondary_char",
800
+ ],
801
+ defaults=["~", "^"]
802
+ )
803
+
804
+ def _extract_caret_anchors_from_line_segment(segment):
805
+ """
806
+ Given source code `segment` corresponding to a FrameSummary, determine:
807
+ - for binary ops, the location of the binary op
808
+ - for indexing and function calls, the location of the brackets.
809
+ `segment` is expected to be a valid Python expression.
810
+ """
811
+ import ast
812
+
813
+ try:
814
+ # Without parentheses, `segment` is parsed as a statement.
815
+ # Binary ops, subscripts, and calls are expressions, so
816
+ # we can wrap them with parentheses to parse them as
817
+ # (possibly multi-line) expressions.
818
+ # e.g. if we try to highlight the addition in
819
+ # x = (
820
+ # a +
821
+ # b
822
+ # )
823
+ # then we would ast.parse
824
+ # a +
825
+ # b
826
+ # which is not a valid statement because of the newline.
827
+ # Adding brackets makes it a valid expression.
828
+ # (
829
+ # a +
830
+ # b
831
+ # )
832
+ # Line locations will be different than the original,
833
+ # which is taken into account later on.
834
+ tree = ast.parse(f"(\n{segment}\n)")
835
+ except SyntaxError:
836
+ return None
837
+
838
+ if len(tree.body) != 1:
839
+ return None
840
+
841
+ lines = segment.splitlines()
842
+
843
+ def normalize(lineno, offset):
844
+ """Get character index given byte offset"""
845
+ return _byte_offset_to_character_offset(lines[lineno], offset)
846
+
847
+ def next_valid_char(lineno, col):
848
+ """Gets the next valid character index in `lines`, if
849
+ the current location is not valid. Handles empty lines.
850
+ """
851
+ while lineno < len(lines) and col >= len(lines[lineno]):
852
+ col = 0
853
+ lineno += 1
854
+ assert lineno < len(lines) and col < len(lines[lineno])
855
+ return lineno, col
856
+
857
+ def increment(lineno, col):
858
+ """Get the next valid character index in `lines`."""
859
+ col += 1
860
+ lineno, col = next_valid_char(lineno, col)
861
+ return lineno, col
862
+
863
+ def nextline(lineno, col):
864
+ """Get the next valid character at least on the next line"""
865
+ col = 0
866
+ lineno += 1
867
+ lineno, col = next_valid_char(lineno, col)
868
+ return lineno, col
869
+
870
+ def increment_until(lineno, col, stop):
871
+ """Get the next valid non-"\\#" character that satisfies the `stop` predicate"""
872
+ while True:
873
+ ch = lines[lineno][col]
874
+ if ch in "\\#":
875
+ lineno, col = nextline(lineno, col)
876
+ elif not stop(ch):
877
+ lineno, col = increment(lineno, col)
878
+ else:
879
+ break
880
+ return lineno, col
881
+
882
+ def setup_positions(expr, force_valid=True):
883
+ """Get the lineno/col position of the end of `expr`. If `force_valid` is True,
884
+ forces the position to be a valid character (e.g. if the position is beyond the
885
+ end of the line, move to the next line)
886
+ """
887
+ # -2 since end_lineno is 1-indexed and because we added an extra
888
+ # bracket + newline to `segment` when calling ast.parse
889
+ lineno = expr.end_lineno - 2
890
+ col = normalize(lineno, expr.end_col_offset)
891
+ return next_valid_char(lineno, col) if force_valid else (lineno, col)
892
+
893
+ statement = tree.body[0]
894
+ match statement:
895
+ case ast.Expr(expr):
896
+ match expr:
897
+ case ast.BinOp():
898
+ # ast gives these locations for BinOp subexpressions
899
+ # ( left_expr ) + ( right_expr )
900
+ # left^^^^^ right^^^^^
901
+ lineno, col = setup_positions(expr.left)
902
+
903
+ # First operator character is the first non-space/')' character
904
+ lineno, col = increment_until(lineno, col, lambda x: not x.isspace() and x != ')')
905
+
906
+ # binary op is 1 or 2 characters long, on the same line,
907
+ # before the right subexpression
908
+ right_col = col + 1
909
+ if (
910
+ right_col < len(lines[lineno])
911
+ and (
912
+ # operator char should not be in the right subexpression
913
+ expr.right.lineno - 2 > lineno or
914
+ right_col < normalize(expr.right.lineno - 2, expr.right.col_offset)
915
+ )
916
+ and not (ch := lines[lineno][right_col]).isspace()
917
+ and ch not in "\\#"
918
+ ):
919
+ right_col += 1
920
+
921
+ # right_col can be invalid since it is exclusive
922
+ return _Anchors(lineno, col, lineno, right_col)
923
+ case ast.Subscript():
924
+ # ast gives these locations for value and slice subexpressions
925
+ # ( value_expr ) [ slice_expr ]
926
+ # value^^^^^ slice^^^^^
927
+ # subscript^^^^^^^^^^^^^^^^^^^^
928
+
929
+ # find left bracket
930
+ left_lineno, left_col = setup_positions(expr.value)
931
+ left_lineno, left_col = increment_until(left_lineno, left_col, lambda x: x == '[')
932
+ # find right bracket (final character of expression)
933
+ right_lineno, right_col = setup_positions(expr, force_valid=False)
934
+ return _Anchors(left_lineno, left_col, right_lineno, right_col)
935
+ case ast.Call():
936
+ # ast gives these locations for function call expressions
937
+ # ( func_expr ) (args, kwargs)
938
+ # func^^^^^
939
+ # call^^^^^^^^^^^^^^^^^^^^^^^^
940
+
941
+ # find left bracket
942
+ left_lineno, left_col = setup_positions(expr.func)
943
+ left_lineno, left_col = increment_until(left_lineno, left_col, lambda x: x == '(')
944
+ # find right bracket (final character of expression)
945
+ right_lineno, right_col = setup_positions(expr, force_valid=False)
946
+ return _Anchors(left_lineno, left_col, right_lineno, right_col)
947
+
948
+ return None
949
+
950
+ _WIDE_CHAR_SPECIFIERS = "WF"
951
+
952
+ def _display_width(line, offset=None):
953
+ """Calculate the amount of width space the given source
954
+ code segment might take if it were to be displayed on a fixed
955
+ width output device. Supports wide unicode characters and emojis."""
956
+
957
+ if offset is None:
958
+ offset = len(line)
959
+
960
+ # Fast track for ASCII-only strings
961
+ if line.isascii():
962
+ return offset
963
+
964
+ import unicodedata
965
+
966
+ return sum(
967
+ 2 if unicodedata.east_asian_width(char) in _WIDE_CHAR_SPECIFIERS else 1
968
+ for char in line[:offset]
969
+ )
970
+
971
+
972
+
973
+ class _ExceptionPrintContext:
974
+ def __init__(self):
975
+ self.seen = set()
976
+ self.exception_group_depth = 0
977
+ self.need_close = False
978
+
979
+ def indent(self):
980
+ return ' ' * (2 * self.exception_group_depth)
981
+
982
+ def emit(self, text_gen, margin_char=None):
983
+ if margin_char is None:
984
+ margin_char = '|'
985
+ indent_str = self.indent()
986
+ if self.exception_group_depth:
987
+ indent_str += margin_char + ' '
988
+
989
+ if isinstance(text_gen, str):
990
+ yield textwrap.indent(text_gen, indent_str, lambda line: True)
991
+ else:
992
+ for text in text_gen:
993
+ yield textwrap.indent(text, indent_str, lambda line: True)
994
+
995
+
996
+ class TracebackException:
997
+ """An exception ready for rendering.
998
+
999
+ The traceback module captures enough attributes from the original exception
1000
+ to this intermediary form to ensure that no references are held, while
1001
+ still being able to fully print or format it.
1002
+
1003
+ max_group_width and max_group_depth control the formatting of exception
1004
+ groups. The depth refers to the nesting level of the group, and the width
1005
+ refers to the size of a single exception group's exceptions array. The
1006
+ formatted output is truncated when either limit is exceeded.
1007
+
1008
+ Use `from_exception` to create TracebackException instances from exception
1009
+ objects, or the constructor to create TracebackException instances from
1010
+ individual components.
1011
+
1012
+ - :attr:`__cause__` A TracebackException of the original *__cause__*.
1013
+ - :attr:`__context__` A TracebackException of the original *__context__*.
1014
+ - :attr:`exceptions` For exception groups - a list of TracebackException
1015
+ instances for the nested *exceptions*. ``None`` for other exceptions.
1016
+ - :attr:`__suppress_context__` The *__suppress_context__* value from the
1017
+ original exception.
1018
+ - :attr:`stack` A `StackSummary` representing the traceback.
1019
+ - :attr:`exc_type` (deprecated) The class of the original traceback.
1020
+ - :attr:`exc_type_str` String display of exc_type
1021
+ - :attr:`filename` For syntax errors - the filename where the error
1022
+ occurred.
1023
+ - :attr:`lineno` For syntax errors - the linenumber where the error
1024
+ occurred.
1025
+ - :attr:`end_lineno` For syntax errors - the end linenumber where the error
1026
+ occurred. Can be `None` if not present.
1027
+ - :attr:`text` For syntax errors - the text where the error
1028
+ occurred.
1029
+ - :attr:`offset` For syntax errors - the offset into the text where the
1030
+ error occurred.
1031
+ - :attr:`end_offset` For syntax errors - the end offset into the text where
1032
+ the error occurred. Can be `None` if not present.
1033
+ - :attr:`msg` For syntax errors - the compiler error message.
1034
+ """
1035
+
1036
+ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
1037
+ lookup_lines=True, capture_locals=False, compact=False,
1038
+ max_group_width=15, max_group_depth=10, save_exc_type=True, _seen=None):
1039
+ # NB: we need to accept exc_type, exc_value, exc_traceback to
1040
+ # permit backwards compat with the existing API, otherwise we
1041
+ # need stub thunk objects just to glue it together.
1042
+ # Handle loops in __cause__ or __context__.
1043
+ is_recursive_call = _seen is not None
1044
+ if _seen is None:
1045
+ _seen = set()
1046
+ _seen.add(id(exc_value))
1047
+
1048
+ self.max_group_width = max_group_width
1049
+ self.max_group_depth = max_group_depth
1050
+
1051
+ self.stack = StackSummary._extract_from_extended_frame_gen(
1052
+ _walk_tb_with_full_positions(exc_traceback),
1053
+ limit=limit, lookup_lines=lookup_lines,
1054
+ capture_locals=capture_locals)
1055
+
1056
+ self._exc_type = exc_type if save_exc_type else None
1057
+
1058
+ # Capture now to permit freeing resources: only complication is in the
1059
+ # unofficial API _format_final_exc_line
1060
+ self._str = _safe_string(exc_value, 'exception')
1061
+ try:
1062
+ self.__notes__ = getattr(exc_value, '__notes__', None)
1063
+ except Exception as e:
1064
+ self.__notes__ = [
1065
+ f'Ignored error getting __notes__: {_safe_string(e, '__notes__', repr)}']
1066
+
1067
+ self._is_syntax_error = False
1068
+ self._have_exc_type = exc_type is not None
1069
+ if exc_type is not None:
1070
+ self.exc_type_qualname = exc_type.__qualname__
1071
+ self.exc_type_module = exc_type.__module__
1072
+ else:
1073
+ self.exc_type_qualname = None
1074
+ self.exc_type_module = None
1075
+
1076
+ if exc_type and issubclass(exc_type, SyntaxError):
1077
+ # Handle SyntaxError's specially
1078
+ self.filename = exc_value.filename
1079
+ lno = exc_value.lineno
1080
+ self.lineno = str(lno) if lno is not None else None
1081
+ end_lno = exc_value.end_lineno
1082
+ self.end_lineno = str(end_lno) if end_lno is not None else None
1083
+ self.text = exc_value.text
1084
+ self.offset = exc_value.offset
1085
+ self.end_offset = exc_value.end_offset
1086
+ self.msg = exc_value.msg
1087
+ self._is_syntax_error = True
1088
+ elif exc_type and issubclass(exc_type, ImportError) and \
1089
+ getattr(exc_value, "name_from", None) is not None:
1090
+ wrong_name = getattr(exc_value, "name_from", None)
1091
+ suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name)
1092
+ if suggestion:
1093
+ self._str += f". Did you mean: '{suggestion}'?"
1094
+ elif exc_type and issubclass(exc_type, (NameError, AttributeError)) and \
1095
+ getattr(exc_value, "name", None) is not None:
1096
+ wrong_name = getattr(exc_value, "name", None)
1097
+ suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name)
1098
+ if suggestion:
1099
+ self._str += f". Did you mean: '{suggestion}'?"
1100
+ if issubclass(exc_type, NameError):
1101
+ wrong_name = getattr(exc_value, "name", None)
1102
+ if wrong_name is not None and wrong_name in sys.stdlib_module_names:
1103
+ if suggestion:
1104
+ self._str += f" Or did you forget to import '{wrong_name}'?"
1105
+ else:
1106
+ self._str += f". Did you forget to import '{wrong_name}'?"
1107
+ if lookup_lines:
1108
+ self._load_lines()
1109
+ self.__suppress_context__ = \
1110
+ exc_value.__suppress_context__ if exc_value is not None else False
1111
+
1112
+ # Convert __cause__ and __context__ to `TracebackExceptions`s, use a
1113
+ # queue to avoid recursion (only the top-level call gets _seen == None)
1114
+ if not is_recursive_call:
1115
+ queue = [(self, exc_value)]
1116
+ while queue:
1117
+ te, e = queue.pop()
1118
+ if (e is not None and e.__cause__ is not None
1119
+ and id(e.__cause__) not in _seen):
1120
+ cause = TracebackException(
1121
+ type(e.__cause__),
1122
+ e.__cause__,
1123
+ e.__cause__.__traceback__,
1124
+ limit=limit,
1125
+ lookup_lines=lookup_lines,
1126
+ capture_locals=capture_locals,
1127
+ max_group_width=max_group_width,
1128
+ max_group_depth=max_group_depth,
1129
+ _seen=_seen)
1130
+ else:
1131
+ cause = None
1132
+
1133
+ if compact:
1134
+ need_context = (cause is None and
1135
+ e is not None and
1136
+ not e.__suppress_context__)
1137
+ else:
1138
+ need_context = True
1139
+ if (e is not None and e.__context__ is not None
1140
+ and need_context and id(e.__context__) not in _seen):
1141
+ context = TracebackException(
1142
+ type(e.__context__),
1143
+ e.__context__,
1144
+ e.__context__.__traceback__,
1145
+ limit=limit,
1146
+ lookup_lines=lookup_lines,
1147
+ capture_locals=capture_locals,
1148
+ max_group_width=max_group_width,
1149
+ max_group_depth=max_group_depth,
1150
+ _seen=_seen)
1151
+ else:
1152
+ context = None
1153
+
1154
+ if e is not None and isinstance(e, BaseExceptionGroup):
1155
+ exceptions = []
1156
+ for exc in e.exceptions:
1157
+ texc = TracebackException(
1158
+ type(exc),
1159
+ exc,
1160
+ exc.__traceback__,
1161
+ limit=limit,
1162
+ lookup_lines=lookup_lines,
1163
+ capture_locals=capture_locals,
1164
+ max_group_width=max_group_width,
1165
+ max_group_depth=max_group_depth,
1166
+ _seen=_seen)
1167
+ exceptions.append(texc)
1168
+ else:
1169
+ exceptions = None
1170
+
1171
+ te.__cause__ = cause
1172
+ te.__context__ = context
1173
+ te.exceptions = exceptions
1174
+ if cause:
1175
+ queue.append((te.__cause__, e.__cause__))
1176
+ if context:
1177
+ queue.append((te.__context__, e.__context__))
1178
+ if exceptions:
1179
+ queue.extend(zip(te.exceptions, e.exceptions))
1180
+
1181
+ @classmethod
1182
+ def from_exception(cls, exc, *args, **kwargs):
1183
+ """Create a TracebackException from an exception."""
1184
+ return cls(type(exc), exc, exc.__traceback__, *args, **kwargs)
1185
+
1186
+ @property
1187
+ def exc_type(self):
1188
+ warnings.warn('Deprecated in 3.13. Use exc_type_str instead.',
1189
+ DeprecationWarning, stacklevel=2)
1190
+ return self._exc_type
1191
+
1192
+ @property
1193
+ def exc_type_str(self):
1194
+ if not self._have_exc_type:
1195
+ return None
1196
+ stype = self.exc_type_qualname
1197
+ smod = self.exc_type_module
1198
+ if smod not in ("__main__", "builtins"):
1199
+ if not isinstance(smod, str):
1200
+ smod = "<unknown>"
1201
+ stype = smod + '.' + stype
1202
+ return stype
1203
+
1204
+ def _load_lines(self):
1205
+ """Private API. force all lines in the stack to be loaded."""
1206
+ for frame in self.stack:
1207
+ frame.line
1208
+
1209
+ def __eq__(self, other):
1210
+ if isinstance(other, TracebackException):
1211
+ return self.__dict__ == other.__dict__
1212
+ return NotImplemented
1213
+
1214
+ def __str__(self):
1215
+ return self._str
1216
+
1217
+ def format_exception_only(self, *, show_group=False, _depth=0, **kwargs):
1218
+ """Format the exception part of the traceback.
1219
+
1220
+ The return value is a generator of strings, each ending in a newline.
1221
+
1222
+ Generator yields the exception message.
1223
+ For :exc:`SyntaxError` exceptions, it
1224
+ also yields (before the exception message)
1225
+ several lines that (when printed)
1226
+ display detailed information about where the syntax error occurred.
1227
+ Following the message, generator also yields
1228
+ all the exception's ``__notes__``.
1229
+
1230
+ When *show_group* is ``True``, and the exception is an instance of
1231
+ :exc:`BaseExceptionGroup`, the nested exceptions are included as
1232
+ well, recursively, with indentation relative to their nesting depth.
1233
+ """
1234
+ colorize = kwargs.get("colorize", False)
1235
+
1236
+ indent = 3 * _depth * ' '
1237
+ if not self._have_exc_type:
1238
+ yield indent + _format_final_exc_line(None, self._str, colorize=colorize)
1239
+ return
1240
+
1241
+ stype = self.exc_type_str
1242
+ if not self._is_syntax_error:
1243
+ if _depth > 0:
1244
+ # Nested exceptions needs correct handling of multiline messages.
1245
+ formatted = _format_final_exc_line(
1246
+ stype, self._str, insert_final_newline=False, colorize=colorize
1247
+ ).split('\n')
1248
+ yield from [
1249
+ indent + l + '\n'
1250
+ for l in formatted
1251
+ ]
1252
+ else:
1253
+ yield _format_final_exc_line(stype, self._str, colorize=colorize)
1254
+ else:
1255
+ yield from [indent + l for l in self._format_syntax_error(stype, colorize=colorize)]
1256
+
1257
+ if (
1258
+ isinstance(self.__notes__, collections.abc.Sequence)
1259
+ and not isinstance(self.__notes__, (str, bytes))
1260
+ ):
1261
+ for note in self.__notes__:
1262
+ note = _safe_string(note, 'note')
1263
+ yield from [indent + l + '\n' for l in note.split('\n')]
1264
+ elif self.__notes__ is not None:
1265
+ yield indent + "{}\n".format(_safe_string(self.__notes__, '__notes__', func=repr))
1266
+
1267
+ if self.exceptions and show_group:
1268
+ for ex in self.exceptions:
1269
+ yield from ex.format_exception_only(show_group=show_group, _depth=_depth+1, colorize=colorize)
1270
+
1271
+ def _format_syntax_error(self, stype, **kwargs):
1272
+ """Format SyntaxError exceptions (internal helper)."""
1273
+ # Show exactly where the problem was found.
1274
+ colorize = kwargs.get("colorize", False)
1275
+ filename_suffix = ''
1276
+ if self.lineno is not None:
1277
+ if colorize:
1278
+ yield ' File {}"{}"{}, line {}{}{}\n'.format(
1279
+ ANSIColors.MAGENTA,
1280
+ self.filename or "<string>",
1281
+ ANSIColors.RESET,
1282
+ ANSIColors.MAGENTA,
1283
+ self.lineno,
1284
+ ANSIColors.RESET,
1285
+ )
1286
+ else:
1287
+ yield ' File "{}", line {}\n'.format(
1288
+ self.filename or "<string>", self.lineno)
1289
+ elif self.filename is not None:
1290
+ filename_suffix = ' ({})'.format(self.filename)
1291
+
1292
+ text = self.text
1293
+ if isinstance(text, str):
1294
+ # text = " foo\n"
1295
+ # rtext = " foo"
1296
+ # ltext = "foo"
1297
+ rtext = text.rstrip('\n')
1298
+ ltext = rtext.lstrip(' \n\f')
1299
+ spaces = len(rtext) - len(ltext)
1300
+ if self.offset is None:
1301
+ yield ' {}\n'.format(ltext)
1302
+ elif isinstance(self.offset, int):
1303
+ offset = self.offset
1304
+ if self.lineno == self.end_lineno:
1305
+ end_offset = (
1306
+ self.end_offset
1307
+ if (
1308
+ isinstance(self.end_offset, int)
1309
+ and self.end_offset != 0
1310
+ )
1311
+ else offset
1312
+ )
1313
+ else:
1314
+ end_offset = len(rtext) + 1
1315
+
1316
+ if self.text and offset > len(self.text):
1317
+ offset = len(rtext) + 1
1318
+ if self.text and end_offset > len(self.text):
1319
+ end_offset = len(rtext) + 1
1320
+ if offset >= end_offset or end_offset < 0:
1321
+ end_offset = offset + 1
1322
+
1323
+ # Convert 1-based column offset to 0-based index into stripped text
1324
+ colno = offset - 1 - spaces
1325
+ end_colno = end_offset - 1 - spaces
1326
+ caretspace = ' '
1327
+ if colno >= 0:
1328
+ # non-space whitespace (likes tabs) must be kept for alignment
1329
+ caretspace = ((c if c.isspace() else ' ') for c in ltext[:colno])
1330
+ start_color = end_color = ""
1331
+ if colorize:
1332
+ # colorize from colno to end_colno
1333
+ ltext = (
1334
+ ltext[:colno] +
1335
+ ANSIColors.BOLD_RED + ltext[colno:end_colno] + ANSIColors.RESET +
1336
+ ltext[end_colno:]
1337
+ )
1338
+ start_color = ANSIColors.BOLD_RED
1339
+ end_color = ANSIColors.RESET
1340
+ yield ' {}\n'.format(ltext)
1341
+ yield ' {}{}{}{}\n'.format(
1342
+ "".join(caretspace),
1343
+ start_color,
1344
+ ('^' * (end_colno - colno)),
1345
+ end_color,
1346
+ )
1347
+ else:
1348
+ yield ' {}\n'.format(ltext)
1349
+ msg = self.msg or "<no detail available>"
1350
+ if colorize:
1351
+ yield "{}{}{}: {}{}{}{}\n".format(
1352
+ ANSIColors.BOLD_MAGENTA,
1353
+ stype,
1354
+ ANSIColors.RESET,
1355
+ ANSIColors.MAGENTA,
1356
+ msg,
1357
+ ANSIColors.RESET,
1358
+ filename_suffix)
1359
+ else:
1360
+ yield "{}: {}{}\n".format(stype, msg, filename_suffix)
1361
+
1362
+ def format(self, *, chain=True, _ctx=None, **kwargs):
1363
+ """Format the exception.
1364
+
1365
+ If chain is not *True*, *__cause__* and *__context__* will not be formatted.
1366
+
1367
+ The return value is a generator of strings, each ending in a newline and
1368
+ some containing internal newlines. `print_exception` is a wrapper around
1369
+ this method which just prints the lines to a file.
1370
+
1371
+ The message indicating which exception occurred is always the last
1372
+ string in the output.
1373
+ """
1374
+ colorize = kwargs.get("colorize", False)
1375
+ if _ctx is None:
1376
+ _ctx = _ExceptionPrintContext()
1377
+
1378
+ output = []
1379
+ exc = self
1380
+ if chain:
1381
+ while exc:
1382
+ if exc.__cause__ is not None:
1383
+ chained_msg = _cause_message
1384
+ chained_exc = exc.__cause__
1385
+ elif (exc.__context__ is not None and
1386
+ not exc.__suppress_context__):
1387
+ chained_msg = _context_message
1388
+ chained_exc = exc.__context__
1389
+ else:
1390
+ chained_msg = None
1391
+ chained_exc = None
1392
+
1393
+ output.append((chained_msg, exc))
1394
+ exc = chained_exc
1395
+ else:
1396
+ output.append((None, exc))
1397
+
1398
+ for msg, exc in reversed(output):
1399
+ if msg is not None:
1400
+ yield from _ctx.emit(msg)
1401
+ if exc.exceptions is None:
1402
+ if exc.stack:
1403
+ yield from _ctx.emit('Traceback (most recent call last):\n')
1404
+ yield from _ctx.emit(exc.stack.format(colorize=colorize))
1405
+ yield from _ctx.emit(exc.format_exception_only(colorize=colorize))
1406
+ elif _ctx.exception_group_depth > self.max_group_depth:
1407
+ # exception group, but depth exceeds limit
1408
+ yield from _ctx.emit(
1409
+ f"... (max_group_depth is {self.max_group_depth})\n")
1410
+ else:
1411
+ # format exception group
1412
+ is_toplevel = (_ctx.exception_group_depth == 0)
1413
+ if is_toplevel:
1414
+ _ctx.exception_group_depth += 1
1415
+
1416
+ if exc.stack:
1417
+ yield from _ctx.emit(
1418
+ 'Exception Group Traceback (most recent call last):\n',
1419
+ margin_char = '+' if is_toplevel else None)
1420
+ yield from _ctx.emit(exc.stack.format(colorize=colorize))
1421
+
1422
+ yield from _ctx.emit(exc.format_exception_only(colorize=colorize))
1423
+ num_excs = len(exc.exceptions)
1424
+ if num_excs <= self.max_group_width:
1425
+ n = num_excs
1426
+ else:
1427
+ n = self.max_group_width + 1
1428
+ _ctx.need_close = False
1429
+ for i in range(n):
1430
+ last_exc = (i == n-1)
1431
+ if last_exc:
1432
+ # The closing frame may be added by a recursive call
1433
+ _ctx.need_close = True
1434
+
1435
+ if self.max_group_width is not None:
1436
+ truncated = (i >= self.max_group_width)
1437
+ else:
1438
+ truncated = False
1439
+ title = f'{i+1}' if not truncated else '...'
1440
+ yield (_ctx.indent() +
1441
+ ('+-' if i==0 else ' ') +
1442
+ f'+---------------- {title} ----------------\n')
1443
+ _ctx.exception_group_depth += 1
1444
+ if not truncated:
1445
+ yield from exc.exceptions[i].format(chain=chain, _ctx=_ctx, colorize=colorize)
1446
+ else:
1447
+ remaining = num_excs - self.max_group_width
1448
+ plural = 's' if remaining > 1 else ''
1449
+ yield from _ctx.emit(
1450
+ f"and {remaining} more exception{plural}\n")
1451
+
1452
+ if last_exc and _ctx.need_close:
1453
+ yield (_ctx.indent() +
1454
+ "+------------------------------------\n")
1455
+ _ctx.need_close = False
1456
+ _ctx.exception_group_depth -= 1
1457
+
1458
+ if is_toplevel:
1459
+ assert _ctx.exception_group_depth == 1
1460
+ _ctx.exception_group_depth = 0
1461
+
1462
+
1463
+ def print(self, *, file=None, chain=True, **kwargs):
1464
+ """Print the result of self.format(chain=chain) to 'file'."""
1465
+ colorize = kwargs.get("colorize", False)
1466
+ if file is None:
1467
+ file = sys.stderr
1468
+ for line in self.format(chain=chain, colorize=colorize):
1469
+ print(line, file=file, end="")
1470
+
1471
+
1472
+ _MAX_CANDIDATE_ITEMS = 750
1473
+ _MAX_STRING_SIZE = 40
1474
+ _MOVE_COST = 2
1475
+ _CASE_COST = 1
1476
+
1477
+
1478
+ def _substitution_cost(ch_a, ch_b):
1479
+ if ch_a == ch_b:
1480
+ return 0
1481
+ if ch_a.lower() == ch_b.lower():
1482
+ return _CASE_COST
1483
+ return _MOVE_COST
1484
+
1485
+
1486
+ def _get_safe___dir__(obj):
1487
+ # Use obj.__dir__() to avoid a TypeError when calling dir(obj).
1488
+ # See gh-131001 and gh-139933.
1489
+ try:
1490
+ d = obj.__dir__()
1491
+ except TypeError: # when obj is a class
1492
+ d = type(obj).__dir__(obj)
1493
+ return sorted(x for x in d if isinstance(x, str))
1494
+
1495
+
1496
+ def _compute_suggestion_error(exc_value, tb, wrong_name):
1497
+ if wrong_name is None or not isinstance(wrong_name, str):
1498
+ return None
1499
+ if isinstance(exc_value, AttributeError):
1500
+ obj = exc_value.obj
1501
+ try:
1502
+ d = _get_safe___dir__(obj)
1503
+ hide_underscored = (wrong_name[:1] != '_')
1504
+ if hide_underscored and tb is not None:
1505
+ while tb.tb_next is not None:
1506
+ tb = tb.tb_next
1507
+ frame = tb.tb_frame
1508
+ if 'self' in frame.f_locals and frame.f_locals['self'] is obj:
1509
+ hide_underscored = False
1510
+ if hide_underscored:
1511
+ d = [x for x in d if x[:1] != '_']
1512
+ except Exception:
1513
+ return None
1514
+ elif isinstance(exc_value, ImportError):
1515
+ try:
1516
+ mod = __import__(exc_value.name)
1517
+ d = _get_safe___dir__(mod)
1518
+ if wrong_name[:1] != '_':
1519
+ d = [x for x in d if x[:1] != '_']
1520
+ except Exception:
1521
+ return None
1522
+ else:
1523
+ assert isinstance(exc_value, NameError)
1524
+ # find most recent frame
1525
+ if tb is None:
1526
+ return None
1527
+ while tb.tb_next is not None:
1528
+ tb = tb.tb_next
1529
+ frame = tb.tb_frame
1530
+ d = (
1531
+ list(frame.f_locals)
1532
+ + list(frame.f_globals)
1533
+ + list(frame.f_builtins)
1534
+ )
1535
+ d = [x for x in d if isinstance(x, str)]
1536
+
1537
+ # Check first if we are in a method and the instance
1538
+ # has the wrong name as attribute
1539
+ if 'self' in frame.f_locals:
1540
+ self = frame.f_locals['self']
1541
+ try:
1542
+ has_wrong_name = hasattr(self, wrong_name)
1543
+ except Exception:
1544
+ has_wrong_name = False
1545
+ if has_wrong_name:
1546
+ return f"self.{wrong_name}"
1547
+
1548
+ try:
1549
+ import _suggestions
1550
+ except ImportError:
1551
+ pass
1552
+ else:
1553
+ return _suggestions._generate_suggestions(d, wrong_name)
1554
+
1555
+ # Compute closest match
1556
+
1557
+ if len(d) > _MAX_CANDIDATE_ITEMS:
1558
+ return None
1559
+ wrong_name_len = len(wrong_name)
1560
+ if wrong_name_len > _MAX_STRING_SIZE:
1561
+ return None
1562
+ best_distance = wrong_name_len
1563
+ suggestion = None
1564
+ for possible_name in d:
1565
+ if possible_name == wrong_name:
1566
+ # A missing attribute is "found". Don't suggest it (see GH-88821).
1567
+ continue
1568
+ # No more than 1/3 of the involved characters should need changed.
1569
+ max_distance = (len(possible_name) + wrong_name_len + 3) * _MOVE_COST // 6
1570
+ # Don't take matches we've already beaten.
1571
+ max_distance = min(max_distance, best_distance - 1)
1572
+ current_distance = _levenshtein_distance(wrong_name, possible_name, max_distance)
1573
+ if current_distance > max_distance:
1574
+ continue
1575
+ if not suggestion or current_distance < best_distance:
1576
+ suggestion = possible_name
1577
+ best_distance = current_distance
1578
+ return suggestion
1579
+
1580
+
1581
+ def _levenshtein_distance(a, b, max_cost):
1582
+ # A Python implementation of Python/suggestions.c:levenshtein_distance.
1583
+
1584
+ # Both strings are the same
1585
+ if a == b:
1586
+ return 0
1587
+
1588
+ # Trim away common affixes
1589
+ pre = 0
1590
+ while a[pre:] and b[pre:] and a[pre] == b[pre]:
1591
+ pre += 1
1592
+ a = a[pre:]
1593
+ b = b[pre:]
1594
+ post = 0
1595
+ while a[:post or None] and b[:post or None] and a[post-1] == b[post-1]:
1596
+ post -= 1
1597
+ a = a[:post or None]
1598
+ b = b[:post or None]
1599
+ if not a or not b:
1600
+ return _MOVE_COST * (len(a) + len(b))
1601
+ if len(a) > _MAX_STRING_SIZE or len(b) > _MAX_STRING_SIZE:
1602
+ return max_cost + 1
1603
+
1604
+ # Prefer shorter buffer
1605
+ if len(b) < len(a):
1606
+ a, b = b, a
1607
+
1608
+ # Quick fail when a match is impossible
1609
+ if (len(b) - len(a)) * _MOVE_COST > max_cost:
1610
+ return max_cost + 1
1611
+
1612
+ # Instead of producing the whole traditional len(a)-by-len(b)
1613
+ # matrix, we can update just one row in place.
1614
+ # Initialize the buffer row
1615
+ row = list(range(_MOVE_COST, _MOVE_COST * (len(a) + 1), _MOVE_COST))
1616
+
1617
+ result = 0
1618
+ for bindex in range(len(b)):
1619
+ bchar = b[bindex]
1620
+ distance = result = bindex * _MOVE_COST
1621
+ minimum = sys.maxsize
1622
+ for index in range(len(a)):
1623
+ # 1) Previous distance in this row is cost(b[:b_index], a[:index])
1624
+ substitute = distance + _substitution_cost(bchar, a[index])
1625
+ # 2) cost(b[:b_index], a[:index+1]) from previous row
1626
+ distance = row[index]
1627
+ # 3) existing result is cost(b[:b_index+1], a[index])
1628
+
1629
+ insert_delete = min(result, distance) + _MOVE_COST
1630
+ result = min(insert_delete, substitute)
1631
+
1632
+ # cost(b[:b_index+1], a[:index+1])
1633
+ row[index] = result
1634
+ if result < minimum:
1635
+ minimum = result
1636
+ if minimum > max_cost:
1637
+ # Everything in this row is too big, so bail early.
1638
+ return max_cost + 1
1639
+ return result