@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,1865 @@
1
+ """
2
+ The `ast` module helps Python applications to process trees of the Python
3
+ abstract syntax grammar. The abstract syntax itself might change with
4
+ each Python release; this module helps to find out programmatically what
5
+ the current grammar looks like and allows modifications of it.
6
+
7
+ An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as
8
+ a flag to the `compile()` builtin function or by using the `parse()`
9
+ function from this module. The result will be a tree of objects whose
10
+ classes all inherit from `ast.AST`.
11
+
12
+ A modified abstract syntax tree can be compiled into a Python code object
13
+ using the built-in `compile()` function.
14
+
15
+ Additionally various helper functions are provided that make working with
16
+ the trees simpler. The main intention of the helper functions and this
17
+ module in general is to provide an easy to use interface for libraries
18
+ that work tightly with the python syntax (template engines for example).
19
+
20
+ :copyright: Copyright 2008 by Armin Ronacher.
21
+ :license: Python License.
22
+ """
23
+ import sys
24
+ import re
25
+ from _ast import *
26
+ from contextlib import contextmanager, nullcontext
27
+ from enum import IntEnum, auto, _simple_enum
28
+
29
+
30
+ def parse(source, filename='<unknown>', mode='exec', *,
31
+ type_comments=False, feature_version=None, optimize=-1):
32
+ """
33
+ Parse the source into an AST node.
34
+ Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
35
+ Pass type_comments=True to get back type comments where the syntax allows.
36
+ """
37
+ flags = PyCF_ONLY_AST
38
+ if optimize > 0:
39
+ flags |= PyCF_OPTIMIZED_AST
40
+ if type_comments:
41
+ flags |= PyCF_TYPE_COMMENTS
42
+ if feature_version is None:
43
+ feature_version = -1
44
+ elif isinstance(feature_version, tuple):
45
+ major, minor = feature_version # Should be a 2-tuple.
46
+ if major != 3:
47
+ raise ValueError(f"Unsupported major version: {major}")
48
+ feature_version = minor
49
+ # Else it should be an int giving the minor version for 3.x.
50
+ return compile(source, filename, mode, flags,
51
+ _feature_version=feature_version, optimize=optimize)
52
+
53
+
54
+ def literal_eval(node_or_string):
55
+ """
56
+ Evaluate an expression node or a string containing only a Python
57
+ expression. The string or node provided may only consist of the following
58
+ Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
59
+ sets, booleans, and None.
60
+
61
+ Caution: A complex expression can overflow the C stack and cause a crash.
62
+ """
63
+ if isinstance(node_or_string, str):
64
+ node_or_string = parse(node_or_string.lstrip(" \t"), mode='eval')
65
+ if isinstance(node_or_string, Expression):
66
+ node_or_string = node_or_string.body
67
+ def _raise_malformed_node(node):
68
+ msg = "malformed node or string"
69
+ if lno := getattr(node, 'lineno', None):
70
+ msg += f' on line {lno}'
71
+ raise ValueError(msg + f': {node!r}')
72
+ def _convert_num(node):
73
+ if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):
74
+ _raise_malformed_node(node)
75
+ return node.value
76
+ def _convert_signed_num(node):
77
+ if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
78
+ operand = _convert_num(node.operand)
79
+ if isinstance(node.op, UAdd):
80
+ return + operand
81
+ else:
82
+ return - operand
83
+ return _convert_num(node)
84
+ def _convert(node):
85
+ if isinstance(node, Constant):
86
+ return node.value
87
+ elif isinstance(node, Tuple):
88
+ return tuple(map(_convert, node.elts))
89
+ elif isinstance(node, List):
90
+ return list(map(_convert, node.elts))
91
+ elif isinstance(node, Set):
92
+ return set(map(_convert, node.elts))
93
+ elif (isinstance(node, Call) and isinstance(node.func, Name) and
94
+ node.func.id == 'set' and node.args == node.keywords == []):
95
+ return set()
96
+ elif isinstance(node, Dict):
97
+ if len(node.keys) != len(node.values):
98
+ _raise_malformed_node(node)
99
+ return dict(zip(map(_convert, node.keys),
100
+ map(_convert, node.values)))
101
+ elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
102
+ left = _convert_signed_num(node.left)
103
+ right = _convert_num(node.right)
104
+ if isinstance(left, (int, float)) and isinstance(right, complex):
105
+ if isinstance(node.op, Add):
106
+ return left + right
107
+ else:
108
+ return left - right
109
+ return _convert_signed_num(node)
110
+ return _convert(node_or_string)
111
+
112
+
113
+ def dump(
114
+ node, annotate_fields=True, include_attributes=False,
115
+ *,
116
+ indent=None, show_empty=False,
117
+ ):
118
+ """
119
+ Return a formatted dump of the tree in node. This is mainly useful for
120
+ debugging purposes. If annotate_fields is true (by default),
121
+ the returned string will show the names and the values for fields.
122
+ If annotate_fields is false, the result string will be more compact by
123
+ omitting unambiguous field names. Attributes such as line
124
+ numbers and column offsets are not dumped by default. If this is wanted,
125
+ include_attributes can be set to true. If indent is a non-negative
126
+ integer or string, then the tree will be pretty-printed with that indent
127
+ level. None (the default) selects the single line representation.
128
+ If show_empty is False, then empty lists and fields that are None
129
+ will be omitted from the output for better readability.
130
+ """
131
+ def _format(node, level=0):
132
+ if indent is not None:
133
+ level += 1
134
+ prefix = '\n' + indent * level
135
+ sep = ',\n' + indent * level
136
+ else:
137
+ prefix = ''
138
+ sep = ', '
139
+ if isinstance(node, AST):
140
+ cls = type(node)
141
+ args = []
142
+ args_buffer = []
143
+ allsimple = True
144
+ keywords = annotate_fields
145
+ for name in node._fields:
146
+ try:
147
+ value = getattr(node, name)
148
+ except AttributeError:
149
+ keywords = True
150
+ continue
151
+ if value is None and getattr(cls, name, ...) is None:
152
+ keywords = True
153
+ continue
154
+ if not show_empty:
155
+ if value == []:
156
+ field_type = cls._field_types.get(name, object)
157
+ if getattr(field_type, '__origin__', ...) is list:
158
+ if not keywords:
159
+ args_buffer.append(repr(value))
160
+ continue
161
+ if not keywords:
162
+ args.extend(args_buffer)
163
+ args_buffer = []
164
+ value, simple = _format(value, level)
165
+ allsimple = allsimple and simple
166
+ if keywords:
167
+ args.append('%s=%s' % (name, value))
168
+ else:
169
+ args.append(value)
170
+ if include_attributes and node._attributes:
171
+ for name in node._attributes:
172
+ try:
173
+ value = getattr(node, name)
174
+ except AttributeError:
175
+ continue
176
+ if value is None and getattr(cls, name, ...) is None:
177
+ continue
178
+ value, simple = _format(value, level)
179
+ allsimple = allsimple and simple
180
+ args.append('%s=%s' % (name, value))
181
+ if allsimple and len(args) <= 3:
182
+ return '%s(%s)' % (node.__class__.__name__, ', '.join(args)), not args
183
+ return '%s(%s%s)' % (node.__class__.__name__, prefix, sep.join(args)), False
184
+ elif isinstance(node, list):
185
+ if not node:
186
+ return '[]', True
187
+ return '[%s%s]' % (prefix, sep.join(_format(x, level)[0] for x in node)), False
188
+ return repr(node), True
189
+
190
+ if not isinstance(node, AST):
191
+ raise TypeError('expected AST, got %r' % node.__class__.__name__)
192
+ if indent is not None and not isinstance(indent, str):
193
+ indent = ' ' * indent
194
+ return _format(node)[0]
195
+
196
+
197
+ def copy_location(new_node, old_node):
198
+ """
199
+ Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset`
200
+ attributes) from *old_node* to *new_node* if possible, and return *new_node*.
201
+ """
202
+ for attr in 'lineno', 'col_offset', 'end_lineno', 'end_col_offset':
203
+ if attr in old_node._attributes and attr in new_node._attributes:
204
+ value = getattr(old_node, attr, None)
205
+ # end_lineno and end_col_offset are optional attributes, and they
206
+ # should be copied whether the value is None or not.
207
+ if value is not None or (
208
+ hasattr(old_node, attr) and attr.startswith("end_")
209
+ ):
210
+ setattr(new_node, attr, value)
211
+ return new_node
212
+
213
+
214
+ def fix_missing_locations(node):
215
+ """
216
+ When you compile a node tree with compile(), the compiler expects lineno and
217
+ col_offset attributes for every node that supports them. This is rather
218
+ tedious to fill in for generated nodes, so this helper adds these attributes
219
+ recursively where not already set, by setting them to the values of the
220
+ parent node. It works recursively starting at *node*.
221
+ """
222
+ def _fix(node, lineno, col_offset, end_lineno, end_col_offset):
223
+ if 'lineno' in node._attributes:
224
+ if not hasattr(node, 'lineno'):
225
+ node.lineno = lineno
226
+ else:
227
+ lineno = node.lineno
228
+ if 'end_lineno' in node._attributes:
229
+ if getattr(node, 'end_lineno', None) is None:
230
+ node.end_lineno = end_lineno
231
+ else:
232
+ end_lineno = node.end_lineno
233
+ if 'col_offset' in node._attributes:
234
+ if not hasattr(node, 'col_offset'):
235
+ node.col_offset = col_offset
236
+ else:
237
+ col_offset = node.col_offset
238
+ if 'end_col_offset' in node._attributes:
239
+ if getattr(node, 'end_col_offset', None) is None:
240
+ node.end_col_offset = end_col_offset
241
+ else:
242
+ end_col_offset = node.end_col_offset
243
+ for child in iter_child_nodes(node):
244
+ _fix(child, lineno, col_offset, end_lineno, end_col_offset)
245
+ _fix(node, 1, 0, 1, 0)
246
+ return node
247
+
248
+
249
+ def increment_lineno(node, n=1):
250
+ """
251
+ Increment the line number and end line number of each node in the tree
252
+ starting at *node* by *n*. This is useful to "move code" to a different
253
+ location in a file.
254
+ """
255
+ for child in walk(node):
256
+ # TypeIgnore is a special case where lineno is not an attribute
257
+ # but rather a field of the node itself.
258
+ if isinstance(child, TypeIgnore):
259
+ child.lineno = getattr(child, 'lineno', 0) + n
260
+ continue
261
+
262
+ if 'lineno' in child._attributes:
263
+ child.lineno = getattr(child, 'lineno', 0) + n
264
+ if (
265
+ "end_lineno" in child._attributes
266
+ and (end_lineno := getattr(child, "end_lineno", 0)) is not None
267
+ ):
268
+ child.end_lineno = end_lineno + n
269
+ return node
270
+
271
+
272
+ def iter_fields(node):
273
+ """
274
+ Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
275
+ that is present on *node*.
276
+ """
277
+ for field in node._fields:
278
+ try:
279
+ yield field, getattr(node, field)
280
+ except AttributeError:
281
+ pass
282
+
283
+
284
+ def iter_child_nodes(node):
285
+ """
286
+ Yield all direct child nodes of *node*, that is, all fields that are nodes
287
+ and all items of fields that are lists of nodes.
288
+ """
289
+ for name, field in iter_fields(node):
290
+ if isinstance(field, AST):
291
+ yield field
292
+ elif isinstance(field, list):
293
+ for item in field:
294
+ if isinstance(item, AST):
295
+ yield item
296
+
297
+
298
+ def get_docstring(node, clean=True):
299
+ """
300
+ Return the docstring for the given node or None if no docstring can
301
+ be found. If the node provided does not have docstrings a TypeError
302
+ will be raised.
303
+
304
+ If *clean* is `True`, all tabs are expanded to spaces and any whitespace
305
+ that can be uniformly removed from the second line onwards is removed.
306
+ """
307
+ if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
308
+ raise TypeError("%r can't have docstrings" % node.__class__.__name__)
309
+ if not(node.body and isinstance(node.body[0], Expr)):
310
+ return None
311
+ node = node.body[0].value
312
+ if isinstance(node, Constant) and isinstance(node.value, str):
313
+ text = node.value
314
+ else:
315
+ return None
316
+ if clean:
317
+ import inspect
318
+ text = inspect.cleandoc(text)
319
+ return text
320
+
321
+
322
+ _line_pattern = re.compile(r"(.*?(?:\r\n|\n|\r|$))")
323
+ def _splitlines_no_ff(source, maxlines=None):
324
+ """Split a string into lines ignoring form feed and other chars.
325
+
326
+ This mimics how the Python parser splits source code.
327
+ """
328
+ lines = []
329
+ for lineno, match in enumerate(_line_pattern.finditer(source), 1):
330
+ if maxlines is not None and lineno > maxlines:
331
+ break
332
+ lines.append(match[0])
333
+ return lines
334
+
335
+
336
+ def _pad_whitespace(source):
337
+ r"""Replace all chars except '\f\t' in a line with spaces."""
338
+ result = ''
339
+ for c in source:
340
+ if c in '\f\t':
341
+ result += c
342
+ else:
343
+ result += ' '
344
+ return result
345
+
346
+
347
+ def get_source_segment(source, node, *, padded=False):
348
+ """Get source code segment of the *source* that generated *node*.
349
+
350
+ If some location information (`lineno`, `end_lineno`, `col_offset`,
351
+ or `end_col_offset`) is missing, return None.
352
+
353
+ If *padded* is `True`, the first line of a multi-line statement will
354
+ be padded with spaces to match its original position.
355
+ """
356
+ try:
357
+ if node.end_lineno is None or node.end_col_offset is None:
358
+ return None
359
+ lineno = node.lineno - 1
360
+ end_lineno = node.end_lineno - 1
361
+ col_offset = node.col_offset
362
+ end_col_offset = node.end_col_offset
363
+ except AttributeError:
364
+ return None
365
+
366
+ lines = _splitlines_no_ff(source, maxlines=end_lineno+1)
367
+ if end_lineno == lineno:
368
+ return lines[lineno].encode()[col_offset:end_col_offset].decode()
369
+
370
+ if padded:
371
+ padding = _pad_whitespace(lines[lineno].encode()[:col_offset].decode())
372
+ else:
373
+ padding = ''
374
+
375
+ first = padding + lines[lineno].encode()[col_offset:].decode()
376
+ last = lines[end_lineno].encode()[:end_col_offset].decode()
377
+ lines = lines[lineno+1:end_lineno]
378
+
379
+ lines.insert(0, first)
380
+ lines.append(last)
381
+ return ''.join(lines)
382
+
383
+
384
+ def walk(node):
385
+ """
386
+ Recursively yield all descendant nodes in the tree starting at *node*
387
+ (including *node* itself), in no specified order. This is useful if you
388
+ only want to modify nodes in place and don't care about the context.
389
+ """
390
+ from collections import deque
391
+ todo = deque([node])
392
+ while todo:
393
+ node = todo.popleft()
394
+ todo.extend(iter_child_nodes(node))
395
+ yield node
396
+
397
+
398
+ class NodeVisitor(object):
399
+ """
400
+ A node visitor base class that walks the abstract syntax tree and calls a
401
+ visitor function for every node found. This function may return a value
402
+ which is forwarded by the `visit` method.
403
+
404
+ This class is meant to be subclassed, with the subclass adding visitor
405
+ methods.
406
+
407
+ Per default the visitor functions for the nodes are ``'visit_'`` +
408
+ class name of the node. So a `TryFinally` node visit function would
409
+ be `visit_TryFinally`. This behavior can be changed by overriding
410
+ the `visit` method. If no visitor function exists for a node
411
+ (return value `None`) the `generic_visit` visitor is used instead.
412
+
413
+ Don't use the `NodeVisitor` if you want to apply changes to nodes during
414
+ traversing. For this a special visitor exists (`NodeTransformer`) that
415
+ allows modifications.
416
+ """
417
+
418
+ def visit(self, node):
419
+ """Visit a node."""
420
+ method = 'visit_' + node.__class__.__name__
421
+ visitor = getattr(self, method, self.generic_visit)
422
+ return visitor(node)
423
+
424
+ def generic_visit(self, node):
425
+ """Called if no explicit visitor function exists for a node."""
426
+ for field, value in iter_fields(node):
427
+ if isinstance(value, list):
428
+ for item in value:
429
+ if isinstance(item, AST):
430
+ self.visit(item)
431
+ elif isinstance(value, AST):
432
+ self.visit(value)
433
+
434
+ def visit_Constant(self, node):
435
+ value = node.value
436
+ type_name = _const_node_type_names.get(type(value))
437
+ if type_name is None:
438
+ for cls, name in _const_node_type_names.items():
439
+ if isinstance(value, cls):
440
+ type_name = name
441
+ break
442
+ if type_name is not None:
443
+ method = 'visit_' + type_name
444
+ try:
445
+ visitor = getattr(self, method)
446
+ except AttributeError:
447
+ pass
448
+ else:
449
+ import warnings
450
+ warnings.warn(f"{method} is deprecated; add visit_Constant",
451
+ DeprecationWarning, 2)
452
+ return visitor(node)
453
+ return self.generic_visit(node)
454
+
455
+
456
+ class NodeTransformer(NodeVisitor):
457
+ """
458
+ A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
459
+ allows modification of nodes.
460
+
461
+ The `NodeTransformer` will walk the AST and use the return value of the
462
+ visitor methods to replace or remove the old node. If the return value of
463
+ the visitor method is ``None``, the node will be removed from its location,
464
+ otherwise it is replaced with the return value. The return value may be the
465
+ original node in which case no replacement takes place.
466
+
467
+ Here is an example transformer that rewrites all occurrences of name lookups
468
+ (``foo``) to ``data['foo']``::
469
+
470
+ class RewriteName(NodeTransformer):
471
+
472
+ def visit_Name(self, node):
473
+ return Subscript(
474
+ value=Name(id='data', ctx=Load()),
475
+ slice=Constant(value=node.id),
476
+ ctx=node.ctx
477
+ )
478
+
479
+ Keep in mind that if the node you're operating on has child nodes you must
480
+ either transform the child nodes yourself or call the :meth:`generic_visit`
481
+ method for the node first.
482
+
483
+ For nodes that were part of a collection of statements (that applies to all
484
+ statement nodes), the visitor may also return a list of nodes rather than
485
+ just a single node.
486
+
487
+ Usually you use the transformer like this::
488
+
489
+ node = YourTransformer().visit(node)
490
+ """
491
+
492
+ def generic_visit(self, node):
493
+ for field, old_value in iter_fields(node):
494
+ if isinstance(old_value, list):
495
+ new_values = []
496
+ for value in old_value:
497
+ if isinstance(value, AST):
498
+ value = self.visit(value)
499
+ if value is None:
500
+ continue
501
+ elif not isinstance(value, AST):
502
+ new_values.extend(value)
503
+ continue
504
+ new_values.append(value)
505
+ old_value[:] = new_values
506
+ elif isinstance(old_value, AST):
507
+ new_node = self.visit(old_value)
508
+ if new_node is None:
509
+ delattr(node, field)
510
+ else:
511
+ setattr(node, field, new_node)
512
+ return node
513
+
514
+
515
+ _DEPRECATED_VALUE_ALIAS_MESSAGE = (
516
+ "{name} is deprecated and will be removed in Python {remove}; use value instead"
517
+ )
518
+ _DEPRECATED_CLASS_MESSAGE = (
519
+ "{name} is deprecated and will be removed in Python {remove}; "
520
+ "use ast.Constant instead"
521
+ )
522
+
523
+
524
+ # If the ast module is loaded more than once, only add deprecated methods once
525
+ if not hasattr(Constant, 'n'):
526
+ # The following code is for backward compatibility.
527
+ # It will be removed in future.
528
+
529
+ def _n_getter(self):
530
+ """Deprecated. Use value instead."""
531
+ import warnings
532
+ warnings._deprecated(
533
+ "Attribute n", message=_DEPRECATED_VALUE_ALIAS_MESSAGE, remove=(3, 14)
534
+ )
535
+ return self.value
536
+
537
+ def _n_setter(self, value):
538
+ import warnings
539
+ warnings._deprecated(
540
+ "Attribute n", message=_DEPRECATED_VALUE_ALIAS_MESSAGE, remove=(3, 14)
541
+ )
542
+ self.value = value
543
+
544
+ def _s_getter(self):
545
+ """Deprecated. Use value instead."""
546
+ import warnings
547
+ warnings._deprecated(
548
+ "Attribute s", message=_DEPRECATED_VALUE_ALIAS_MESSAGE, remove=(3, 14)
549
+ )
550
+ return self.value
551
+
552
+ def _s_setter(self, value):
553
+ import warnings
554
+ warnings._deprecated(
555
+ "Attribute s", message=_DEPRECATED_VALUE_ALIAS_MESSAGE, remove=(3, 14)
556
+ )
557
+ self.value = value
558
+
559
+ Constant.n = property(_n_getter, _n_setter)
560
+ Constant.s = property(_s_getter, _s_setter)
561
+
562
+ class _ABC(type):
563
+
564
+ def __init__(cls, *args):
565
+ cls.__doc__ = """Deprecated AST node class. Use ast.Constant instead"""
566
+
567
+ def __instancecheck__(cls, inst):
568
+ if cls in _const_types:
569
+ import warnings
570
+ warnings._deprecated(
571
+ f"ast.{cls.__qualname__}",
572
+ message=_DEPRECATED_CLASS_MESSAGE,
573
+ remove=(3, 14)
574
+ )
575
+ if not isinstance(inst, Constant):
576
+ return False
577
+ if cls in _const_types:
578
+ try:
579
+ value = inst.value
580
+ except AttributeError:
581
+ return False
582
+ else:
583
+ return (
584
+ isinstance(value, _const_types[cls]) and
585
+ not isinstance(value, _const_types_not.get(cls, ()))
586
+ )
587
+ return type.__instancecheck__(cls, inst)
588
+
589
+ def _new(cls, *args, **kwargs):
590
+ for key in kwargs:
591
+ if key not in cls._fields:
592
+ # arbitrary keyword arguments are accepted
593
+ continue
594
+ pos = cls._fields.index(key)
595
+ if pos < len(args):
596
+ raise TypeError(f"{cls.__name__} got multiple values for argument {key!r}")
597
+ if cls in _const_types:
598
+ import warnings
599
+ warnings._deprecated(
600
+ f"ast.{cls.__qualname__}", message=_DEPRECATED_CLASS_MESSAGE, remove=(3, 14)
601
+ )
602
+ return Constant(*args, **kwargs)
603
+ return Constant.__new__(cls, *args, **kwargs)
604
+
605
+ class Num(Constant, metaclass=_ABC):
606
+ _fields = ('n',)
607
+ __new__ = _new
608
+
609
+ class Str(Constant, metaclass=_ABC):
610
+ _fields = ('s',)
611
+ __new__ = _new
612
+
613
+ class Bytes(Constant, metaclass=_ABC):
614
+ _fields = ('s',)
615
+ __new__ = _new
616
+
617
+ class NameConstant(Constant, metaclass=_ABC):
618
+ __new__ = _new
619
+
620
+ class Ellipsis(Constant, metaclass=_ABC):
621
+ _fields = ()
622
+
623
+ def __new__(cls, *args, **kwargs):
624
+ if cls is _ast_Ellipsis:
625
+ import warnings
626
+ warnings._deprecated(
627
+ "ast.Ellipsis", message=_DEPRECATED_CLASS_MESSAGE, remove=(3, 14)
628
+ )
629
+ return Constant(..., *args, **kwargs)
630
+ return Constant.__new__(cls, *args, **kwargs)
631
+
632
+ # Keep another reference to Ellipsis in the global namespace
633
+ # so it can be referenced in Ellipsis.__new__
634
+ # (The original "Ellipsis" name is removed from the global namespace later on)
635
+ _ast_Ellipsis = Ellipsis
636
+
637
+ _const_types = {
638
+ Num: (int, float, complex),
639
+ Str: (str,),
640
+ Bytes: (bytes,),
641
+ NameConstant: (type(None), bool),
642
+ Ellipsis: (type(...),),
643
+ }
644
+ _const_types_not = {
645
+ Num: (bool,),
646
+ }
647
+
648
+ _const_node_type_names = {
649
+ bool: 'NameConstant', # should be before int
650
+ type(None): 'NameConstant',
651
+ int: 'Num',
652
+ float: 'Num',
653
+ complex: 'Num',
654
+ str: 'Str',
655
+ bytes: 'Bytes',
656
+ type(...): 'Ellipsis',
657
+ }
658
+
659
+ class slice(AST):
660
+ """Deprecated AST node class."""
661
+
662
+ class Index(slice):
663
+ """Deprecated AST node class. Use the index value directly instead."""
664
+ def __new__(cls, value, **kwargs):
665
+ return value
666
+
667
+ class ExtSlice(slice):
668
+ """Deprecated AST node class. Use ast.Tuple instead."""
669
+ def __new__(cls, dims=(), **kwargs):
670
+ return Tuple(list(dims), Load(), **kwargs)
671
+
672
+ # If the ast module is loaded more than once, only add deprecated methods once
673
+ if not hasattr(Tuple, 'dims'):
674
+ # The following code is for backward compatibility.
675
+ # It will be removed in future.
676
+
677
+ def _dims_getter(self):
678
+ """Deprecated. Use elts instead."""
679
+ return self.elts
680
+
681
+ def _dims_setter(self, value):
682
+ self.elts = value
683
+
684
+ Tuple.dims = property(_dims_getter, _dims_setter)
685
+
686
+ class Suite(mod):
687
+ """Deprecated AST node class. Unused in Python 3."""
688
+
689
+ class AugLoad(expr_context):
690
+ """Deprecated AST node class. Unused in Python 3."""
691
+
692
+ class AugStore(expr_context):
693
+ """Deprecated AST node class. Unused in Python 3."""
694
+
695
+ class Param(expr_context):
696
+ """Deprecated AST node class. Unused in Python 3."""
697
+
698
+
699
+ # Large float and imaginary literals get turned into infinities in the AST.
700
+ # We unparse those infinities to INFSTR.
701
+ _INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)
702
+
703
+ @_simple_enum(IntEnum)
704
+ class _Precedence:
705
+ """Precedence table that originated from python grammar."""
706
+
707
+ NAMED_EXPR = auto() # <target> := <expr1>
708
+ TUPLE = auto() # <expr1>, <expr2>
709
+ YIELD = auto() # 'yield', 'yield from'
710
+ TEST = auto() # 'if'-'else', 'lambda'
711
+ OR = auto() # 'or'
712
+ AND = auto() # 'and'
713
+ NOT = auto() # 'not'
714
+ CMP = auto() # '<', '>', '==', '>=', '<=', '!=',
715
+ # 'in', 'not in', 'is', 'is not'
716
+ EXPR = auto()
717
+ BOR = EXPR # '|'
718
+ BXOR = auto() # '^'
719
+ BAND = auto() # '&'
720
+ SHIFT = auto() # '<<', '>>'
721
+ ARITH = auto() # '+', '-'
722
+ TERM = auto() # '*', '@', '/', '%', '//'
723
+ FACTOR = auto() # unary '+', '-', '~'
724
+ POWER = auto() # '**'
725
+ AWAIT = auto() # 'await'
726
+ ATOM = auto()
727
+
728
+ def next(self):
729
+ try:
730
+ return self.__class__(self + 1)
731
+ except ValueError:
732
+ return self
733
+
734
+
735
+ _SINGLE_QUOTES = ("'", '"')
736
+ _MULTI_QUOTES = ('"""', "'''")
737
+ _ALL_QUOTES = (*_SINGLE_QUOTES, *_MULTI_QUOTES)
738
+
739
+ class _Unparser(NodeVisitor):
740
+ """Methods in this class recursively traverse an AST and
741
+ output source code for the abstract syntax; original formatting
742
+ is disregarded."""
743
+
744
+ def __init__(self):
745
+ self._source = []
746
+ self._precedences = {}
747
+ self._type_ignores = {}
748
+ self._indent = 0
749
+ self._in_try_star = False
750
+
751
+ def interleave(self, inter, f, seq):
752
+ """Call f on each item in seq, calling inter() in between."""
753
+ seq = iter(seq)
754
+ try:
755
+ f(next(seq))
756
+ except StopIteration:
757
+ pass
758
+ else:
759
+ for x in seq:
760
+ inter()
761
+ f(x)
762
+
763
+ def items_view(self, traverser, items):
764
+ """Traverse and separate the given *items* with a comma and append it to
765
+ the buffer. If *items* is a single item sequence, a trailing comma
766
+ will be added."""
767
+ if len(items) == 1:
768
+ traverser(items[0])
769
+ self.write(",")
770
+ else:
771
+ self.interleave(lambda: self.write(", "), traverser, items)
772
+
773
+ def maybe_newline(self):
774
+ """Adds a newline if it isn't the start of generated source"""
775
+ if self._source:
776
+ self.write("\n")
777
+
778
+ def fill(self, text=""):
779
+ """Indent a piece of text and append it, according to the current
780
+ indentation level"""
781
+ self.maybe_newline()
782
+ self.write(" " * self._indent + text)
783
+
784
+ def write(self, *text):
785
+ """Add new source parts"""
786
+ self._source.extend(text)
787
+
788
+ @contextmanager
789
+ def buffered(self, buffer = None):
790
+ if buffer is None:
791
+ buffer = []
792
+
793
+ original_source = self._source
794
+ self._source = buffer
795
+ yield buffer
796
+ self._source = original_source
797
+
798
+ @contextmanager
799
+ def block(self, *, extra = None):
800
+ """A context manager for preparing the source for blocks. It adds
801
+ the character':', increases the indentation on enter and decreases
802
+ the indentation on exit. If *extra* is given, it will be directly
803
+ appended after the colon character.
804
+ """
805
+ self.write(":")
806
+ if extra:
807
+ self.write(extra)
808
+ self._indent += 1
809
+ yield
810
+ self._indent -= 1
811
+
812
+ @contextmanager
813
+ def delimit(self, start, end):
814
+ """A context manager for preparing the source for expressions. It adds
815
+ *start* to the buffer and enters, after exit it adds *end*."""
816
+
817
+ self.write(start)
818
+ yield
819
+ self.write(end)
820
+
821
+ def delimit_if(self, start, end, condition):
822
+ if condition:
823
+ return self.delimit(start, end)
824
+ else:
825
+ return nullcontext()
826
+
827
+ def require_parens(self, precedence, node):
828
+ """Shortcut to adding precedence related parens"""
829
+ return self.delimit_if("(", ")", self.get_precedence(node) > precedence)
830
+
831
+ def get_precedence(self, node):
832
+ return self._precedences.get(node, _Precedence.TEST)
833
+
834
+ def set_precedence(self, precedence, *nodes):
835
+ for node in nodes:
836
+ self._precedences[node] = precedence
837
+
838
+ def get_raw_docstring(self, node):
839
+ """If a docstring node is found in the body of the *node* parameter,
840
+ return that docstring node, None otherwise.
841
+
842
+ Logic mirrored from ``_PyAST_GetDocString``."""
843
+ if not isinstance(
844
+ node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)
845
+ ) or len(node.body) < 1:
846
+ return None
847
+ node = node.body[0]
848
+ if not isinstance(node, Expr):
849
+ return None
850
+ node = node.value
851
+ if isinstance(node, Constant) and isinstance(node.value, str):
852
+ return node
853
+
854
+ def get_type_comment(self, node):
855
+ comment = self._type_ignores.get(node.lineno) or node.type_comment
856
+ if comment is not None:
857
+ return f" # type: {comment}"
858
+
859
+ def traverse(self, node):
860
+ if isinstance(node, list):
861
+ for item in node:
862
+ self.traverse(item)
863
+ else:
864
+ super().visit(node)
865
+
866
+ # Note: as visit() resets the output text, do NOT rely on
867
+ # NodeVisitor.generic_visit to handle any nodes (as it calls back in to
868
+ # the subclass visit() method, which resets self._source to an empty list)
869
+ def visit(self, node):
870
+ """Outputs a source code string that, if converted back to an ast
871
+ (using ast.parse) will generate an AST equivalent to *node*"""
872
+ self._source = []
873
+ self.traverse(node)
874
+ return "".join(self._source)
875
+
876
+ def _write_docstring_and_traverse_body(self, node):
877
+ if (docstring := self.get_raw_docstring(node)):
878
+ self._write_docstring(docstring)
879
+ self.traverse(node.body[1:])
880
+ else:
881
+ self.traverse(node.body)
882
+
883
+ def visit_Module(self, node):
884
+ self._type_ignores = {
885
+ ignore.lineno: f"ignore{ignore.tag}"
886
+ for ignore in node.type_ignores
887
+ }
888
+ self._write_docstring_and_traverse_body(node)
889
+ self._type_ignores.clear()
890
+
891
+ def visit_FunctionType(self, node):
892
+ with self.delimit("(", ")"):
893
+ self.interleave(
894
+ lambda: self.write(", "), self.traverse, node.argtypes
895
+ )
896
+
897
+ self.write(" -> ")
898
+ self.traverse(node.returns)
899
+
900
+ def visit_Expr(self, node):
901
+ self.fill()
902
+ self.set_precedence(_Precedence.YIELD, node.value)
903
+ self.traverse(node.value)
904
+
905
+ def visit_NamedExpr(self, node):
906
+ with self.require_parens(_Precedence.NAMED_EXPR, node):
907
+ self.set_precedence(_Precedence.ATOM, node.target, node.value)
908
+ self.traverse(node.target)
909
+ self.write(" := ")
910
+ self.traverse(node.value)
911
+
912
+ def visit_Import(self, node):
913
+ self.fill("import ")
914
+ self.interleave(lambda: self.write(", "), self.traverse, node.names)
915
+
916
+ def visit_ImportFrom(self, node):
917
+ self.fill("from ")
918
+ self.write("." * (node.level or 0))
919
+ if node.module:
920
+ self.write(node.module)
921
+ self.write(" import ")
922
+ self.interleave(lambda: self.write(", "), self.traverse, node.names)
923
+
924
+ def visit_Assign(self, node):
925
+ self.fill()
926
+ for target in node.targets:
927
+ self.set_precedence(_Precedence.TUPLE, target)
928
+ self.traverse(target)
929
+ self.write(" = ")
930
+ self.traverse(node.value)
931
+ if type_comment := self.get_type_comment(node):
932
+ self.write(type_comment)
933
+
934
+ def visit_AugAssign(self, node):
935
+ self.fill()
936
+ self.traverse(node.target)
937
+ self.write(" " + self.binop[node.op.__class__.__name__] + "= ")
938
+ self.traverse(node.value)
939
+
940
+ def visit_AnnAssign(self, node):
941
+ self.fill()
942
+ with self.delimit_if("(", ")", not node.simple and isinstance(node.target, Name)):
943
+ self.traverse(node.target)
944
+ self.write(": ")
945
+ self.traverse(node.annotation)
946
+ if node.value:
947
+ self.write(" = ")
948
+ self.traverse(node.value)
949
+
950
+ def visit_Return(self, node):
951
+ self.fill("return")
952
+ if node.value:
953
+ self.write(" ")
954
+ self.traverse(node.value)
955
+
956
+ def visit_Pass(self, node):
957
+ self.fill("pass")
958
+
959
+ def visit_Break(self, node):
960
+ self.fill("break")
961
+
962
+ def visit_Continue(self, node):
963
+ self.fill("continue")
964
+
965
+ def visit_Delete(self, node):
966
+ self.fill("del ")
967
+ self.interleave(lambda: self.write(", "), self.traverse, node.targets)
968
+
969
+ def visit_Assert(self, node):
970
+ self.fill("assert ")
971
+ self.traverse(node.test)
972
+ if node.msg:
973
+ self.write(", ")
974
+ self.traverse(node.msg)
975
+
976
+ def visit_Global(self, node):
977
+ self.fill("global ")
978
+ self.interleave(lambda: self.write(", "), self.write, node.names)
979
+
980
+ def visit_Nonlocal(self, node):
981
+ self.fill("nonlocal ")
982
+ self.interleave(lambda: self.write(", "), self.write, node.names)
983
+
984
+ def visit_Await(self, node):
985
+ with self.require_parens(_Precedence.AWAIT, node):
986
+ self.write("await")
987
+ if node.value:
988
+ self.write(" ")
989
+ self.set_precedence(_Precedence.ATOM, node.value)
990
+ self.traverse(node.value)
991
+
992
+ def visit_Yield(self, node):
993
+ with self.require_parens(_Precedence.YIELD, node):
994
+ self.write("yield")
995
+ if node.value:
996
+ self.write(" ")
997
+ self.set_precedence(_Precedence.ATOM, node.value)
998
+ self.traverse(node.value)
999
+
1000
+ def visit_YieldFrom(self, node):
1001
+ with self.require_parens(_Precedence.YIELD, node):
1002
+ self.write("yield from ")
1003
+ if not node.value:
1004
+ raise ValueError("Node can't be used without a value attribute.")
1005
+ self.set_precedence(_Precedence.ATOM, node.value)
1006
+ self.traverse(node.value)
1007
+
1008
+ def visit_Raise(self, node):
1009
+ self.fill("raise")
1010
+ if not node.exc:
1011
+ if node.cause:
1012
+ raise ValueError(f"Node can't use cause without an exception.")
1013
+ return
1014
+ self.write(" ")
1015
+ self.traverse(node.exc)
1016
+ if node.cause:
1017
+ self.write(" from ")
1018
+ self.traverse(node.cause)
1019
+
1020
+ def do_visit_try(self, node):
1021
+ self.fill("try")
1022
+ with self.block():
1023
+ self.traverse(node.body)
1024
+ for ex in node.handlers:
1025
+ self.traverse(ex)
1026
+ if node.orelse:
1027
+ self.fill("else")
1028
+ with self.block():
1029
+ self.traverse(node.orelse)
1030
+ if node.finalbody:
1031
+ self.fill("finally")
1032
+ with self.block():
1033
+ self.traverse(node.finalbody)
1034
+
1035
+ def visit_Try(self, node):
1036
+ prev_in_try_star = self._in_try_star
1037
+ try:
1038
+ self._in_try_star = False
1039
+ self.do_visit_try(node)
1040
+ finally:
1041
+ self._in_try_star = prev_in_try_star
1042
+
1043
+ def visit_TryStar(self, node):
1044
+ prev_in_try_star = self._in_try_star
1045
+ try:
1046
+ self._in_try_star = True
1047
+ self.do_visit_try(node)
1048
+ finally:
1049
+ self._in_try_star = prev_in_try_star
1050
+
1051
+ def visit_ExceptHandler(self, node):
1052
+ self.fill("except*" if self._in_try_star else "except")
1053
+ if node.type:
1054
+ self.write(" ")
1055
+ self.traverse(node.type)
1056
+ if node.name:
1057
+ self.write(" as ")
1058
+ self.write(node.name)
1059
+ with self.block():
1060
+ self.traverse(node.body)
1061
+
1062
+ def visit_ClassDef(self, node):
1063
+ self.maybe_newline()
1064
+ for deco in node.decorator_list:
1065
+ self.fill("@")
1066
+ self.traverse(deco)
1067
+ self.fill("class " + node.name)
1068
+ if hasattr(node, "type_params"):
1069
+ self._type_params_helper(node.type_params)
1070
+ with self.delimit_if("(", ")", condition = node.bases or node.keywords):
1071
+ comma = False
1072
+ for e in node.bases:
1073
+ if comma:
1074
+ self.write(", ")
1075
+ else:
1076
+ comma = True
1077
+ self.traverse(e)
1078
+ for e in node.keywords:
1079
+ if comma:
1080
+ self.write(", ")
1081
+ else:
1082
+ comma = True
1083
+ self.traverse(e)
1084
+
1085
+ with self.block():
1086
+ self._write_docstring_and_traverse_body(node)
1087
+
1088
+ def visit_FunctionDef(self, node):
1089
+ self._function_helper(node, "def")
1090
+
1091
+ def visit_AsyncFunctionDef(self, node):
1092
+ self._function_helper(node, "async def")
1093
+
1094
+ def _function_helper(self, node, fill_suffix):
1095
+ self.maybe_newline()
1096
+ for deco in node.decorator_list:
1097
+ self.fill("@")
1098
+ self.traverse(deco)
1099
+ def_str = fill_suffix + " " + node.name
1100
+ self.fill(def_str)
1101
+ if hasattr(node, "type_params"):
1102
+ self._type_params_helper(node.type_params)
1103
+ with self.delimit("(", ")"):
1104
+ self.traverse(node.args)
1105
+ if node.returns:
1106
+ self.write(" -> ")
1107
+ self.traverse(node.returns)
1108
+ with self.block(extra=self.get_type_comment(node)):
1109
+ self._write_docstring_and_traverse_body(node)
1110
+
1111
+ def _type_params_helper(self, type_params):
1112
+ if type_params is not None and len(type_params) > 0:
1113
+ with self.delimit("[", "]"):
1114
+ self.interleave(lambda: self.write(", "), self.traverse, type_params)
1115
+
1116
+ def visit_TypeVar(self, node):
1117
+ self.write(node.name)
1118
+ if node.bound:
1119
+ self.write(": ")
1120
+ self.traverse(node.bound)
1121
+ if node.default_value:
1122
+ self.write(" = ")
1123
+ self.traverse(node.default_value)
1124
+
1125
+ def visit_TypeVarTuple(self, node):
1126
+ self.write("*" + node.name)
1127
+ if node.default_value:
1128
+ self.write(" = ")
1129
+ self.traverse(node.default_value)
1130
+
1131
+ def visit_ParamSpec(self, node):
1132
+ self.write("**" + node.name)
1133
+ if node.default_value:
1134
+ self.write(" = ")
1135
+ self.traverse(node.default_value)
1136
+
1137
+ def visit_TypeAlias(self, node):
1138
+ self.fill("type ")
1139
+ self.traverse(node.name)
1140
+ self._type_params_helper(node.type_params)
1141
+ self.write(" = ")
1142
+ self.traverse(node.value)
1143
+
1144
+ def visit_For(self, node):
1145
+ self._for_helper("for ", node)
1146
+
1147
+ def visit_AsyncFor(self, node):
1148
+ self._for_helper("async for ", node)
1149
+
1150
+ def _for_helper(self, fill, node):
1151
+ self.fill(fill)
1152
+ self.set_precedence(_Precedence.TUPLE, node.target)
1153
+ self.traverse(node.target)
1154
+ self.write(" in ")
1155
+ self.traverse(node.iter)
1156
+ with self.block(extra=self.get_type_comment(node)):
1157
+ self.traverse(node.body)
1158
+ if node.orelse:
1159
+ self.fill("else")
1160
+ with self.block():
1161
+ self.traverse(node.orelse)
1162
+
1163
+ def visit_If(self, node):
1164
+ self.fill("if ")
1165
+ self.traverse(node.test)
1166
+ with self.block():
1167
+ self.traverse(node.body)
1168
+ # collapse nested ifs into equivalent elifs.
1169
+ while node.orelse and len(node.orelse) == 1 and isinstance(node.orelse[0], If):
1170
+ node = node.orelse[0]
1171
+ self.fill("elif ")
1172
+ self.traverse(node.test)
1173
+ with self.block():
1174
+ self.traverse(node.body)
1175
+ # final else
1176
+ if node.orelse:
1177
+ self.fill("else")
1178
+ with self.block():
1179
+ self.traverse(node.orelse)
1180
+
1181
+ def visit_While(self, node):
1182
+ self.fill("while ")
1183
+ self.traverse(node.test)
1184
+ with self.block():
1185
+ self.traverse(node.body)
1186
+ if node.orelse:
1187
+ self.fill("else")
1188
+ with self.block():
1189
+ self.traverse(node.orelse)
1190
+
1191
+ def visit_With(self, node):
1192
+ self.fill("with ")
1193
+ self.interleave(lambda: self.write(", "), self.traverse, node.items)
1194
+ with self.block(extra=self.get_type_comment(node)):
1195
+ self.traverse(node.body)
1196
+
1197
+ def visit_AsyncWith(self, node):
1198
+ self.fill("async with ")
1199
+ self.interleave(lambda: self.write(", "), self.traverse, node.items)
1200
+ with self.block(extra=self.get_type_comment(node)):
1201
+ self.traverse(node.body)
1202
+
1203
+ def _str_literal_helper(
1204
+ self, string, *, quote_types=_ALL_QUOTES, escape_special_whitespace=False
1205
+ ):
1206
+ """Helper for writing string literals, minimizing escapes.
1207
+ Returns the tuple (string literal to write, possible quote types).
1208
+ """
1209
+ def escape_char(c):
1210
+ # \n and \t are non-printable, but we only escape them if
1211
+ # escape_special_whitespace is True
1212
+ if not escape_special_whitespace and c in "\n\t":
1213
+ return c
1214
+ # Always escape backslashes and other non-printable characters
1215
+ if c == "\\" or not c.isprintable():
1216
+ return c.encode("unicode_escape").decode("ascii")
1217
+ return c
1218
+
1219
+ escaped_string = "".join(map(escape_char, string))
1220
+ possible_quotes = quote_types
1221
+ if "\n" in escaped_string:
1222
+ possible_quotes = [q for q in possible_quotes if q in _MULTI_QUOTES]
1223
+ possible_quotes = [q for q in possible_quotes if q not in escaped_string]
1224
+ if not possible_quotes:
1225
+ # If there aren't any possible_quotes, fallback to using repr
1226
+ # on the original string. Try to use a quote from quote_types,
1227
+ # e.g., so that we use triple quotes for docstrings.
1228
+ string = repr(string)
1229
+ quote = next((q for q in quote_types if string[0] in q), string[0])
1230
+ return string[1:-1], [quote]
1231
+ if escaped_string:
1232
+ # Sort so that we prefer '''"''' over """\""""
1233
+ possible_quotes.sort(key=lambda q: q[0] == escaped_string[-1])
1234
+ # If we're using triple quotes and we'd need to escape a final
1235
+ # quote, escape it
1236
+ if possible_quotes[0][0] == escaped_string[-1]:
1237
+ assert len(possible_quotes[0]) == 3
1238
+ escaped_string = escaped_string[:-1] + "\\" + escaped_string[-1]
1239
+ return escaped_string, possible_quotes
1240
+
1241
+ def _write_str_avoiding_backslashes(self, string, *, quote_types=_ALL_QUOTES):
1242
+ """Write string literal value with a best effort attempt to avoid backslashes."""
1243
+ string, quote_types = self._str_literal_helper(string, quote_types=quote_types)
1244
+ quote_type = quote_types[0]
1245
+ self.write(f"{quote_type}{string}{quote_type}")
1246
+
1247
+ def visit_JoinedStr(self, node):
1248
+ self.write("f")
1249
+
1250
+ fstring_parts = []
1251
+ for value in node.values:
1252
+ with self.buffered() as buffer:
1253
+ self._write_fstring_inner(value)
1254
+ fstring_parts.append(
1255
+ ("".join(buffer), isinstance(value, Constant))
1256
+ )
1257
+
1258
+ new_fstring_parts = []
1259
+ quote_types = list(_ALL_QUOTES)
1260
+ fallback_to_repr = False
1261
+ for value, is_constant in fstring_parts:
1262
+ if is_constant:
1263
+ value, new_quote_types = self._str_literal_helper(
1264
+ value,
1265
+ quote_types=quote_types,
1266
+ escape_special_whitespace=True,
1267
+ )
1268
+ if set(new_quote_types).isdisjoint(quote_types):
1269
+ fallback_to_repr = True
1270
+ break
1271
+ quote_types = new_quote_types
1272
+ else:
1273
+ if "\n" in value:
1274
+ quote_types = [q for q in quote_types if q in _MULTI_QUOTES]
1275
+ assert quote_types
1276
+
1277
+ new_quote_types = [q for q in quote_types if q not in value]
1278
+ if new_quote_types:
1279
+ quote_types = new_quote_types
1280
+ new_fstring_parts.append(value)
1281
+
1282
+ if fallback_to_repr:
1283
+ # If we weren't able to find a quote type that works for all parts
1284
+ # of the JoinedStr, fallback to using repr and triple single quotes.
1285
+ quote_types = ["'''"]
1286
+ new_fstring_parts.clear()
1287
+ for value, is_constant in fstring_parts:
1288
+ if is_constant:
1289
+ value = repr('"' + value) # force repr to use single quotes
1290
+ expected_prefix = "'\""
1291
+ assert value.startswith(expected_prefix), repr(value)
1292
+ value = value[len(expected_prefix):-1]
1293
+ new_fstring_parts.append(value)
1294
+
1295
+ value = "".join(new_fstring_parts)
1296
+ quote_type = quote_types[0]
1297
+ self.write(f"{quote_type}{value}{quote_type}")
1298
+
1299
+ def _write_fstring_inner(self, node, is_format_spec=False):
1300
+ if isinstance(node, JoinedStr):
1301
+ # for both the f-string itself, and format_spec
1302
+ for value in node.values:
1303
+ self._write_fstring_inner(value, is_format_spec=is_format_spec)
1304
+ elif isinstance(node, Constant) and isinstance(node.value, str):
1305
+ value = node.value.replace("{", "{{").replace("}", "}}")
1306
+
1307
+ if is_format_spec:
1308
+ value = value.replace("\\", "\\\\")
1309
+ value = value.replace("'", "\\'")
1310
+ value = value.replace('"', '\\"')
1311
+ value = value.replace("\n", "\\n")
1312
+ self.write(value)
1313
+ elif isinstance(node, FormattedValue):
1314
+ self.visit_FormattedValue(node)
1315
+ else:
1316
+ raise ValueError(f"Unexpected node inside JoinedStr, {node!r}")
1317
+
1318
+ def visit_FormattedValue(self, node):
1319
+ def unparse_inner(inner):
1320
+ unparser = type(self)()
1321
+ unparser.set_precedence(_Precedence.TEST.next(), inner)
1322
+ return unparser.visit(inner)
1323
+
1324
+ with self.delimit("{", "}"):
1325
+ expr = unparse_inner(node.value)
1326
+ if expr.startswith("{"):
1327
+ # Separate pair of opening brackets as "{ {"
1328
+ self.write(" ")
1329
+ self.write(expr)
1330
+ if node.conversion != -1:
1331
+ self.write(f"!{chr(node.conversion)}")
1332
+ if node.format_spec:
1333
+ self.write(":")
1334
+ self._write_fstring_inner(node.format_spec, is_format_spec=True)
1335
+
1336
+ def visit_Name(self, node):
1337
+ self.write(node.id)
1338
+
1339
+ def _write_docstring(self, node):
1340
+ self.fill()
1341
+ if node.kind == "u":
1342
+ self.write("u")
1343
+ self._write_str_avoiding_backslashes(node.value, quote_types=_MULTI_QUOTES)
1344
+
1345
+ def _write_constant(self, value):
1346
+ if isinstance(value, (float, complex)):
1347
+ # Substitute overflowing decimal literal for AST infinities,
1348
+ # and inf - inf for NaNs.
1349
+ self.write(
1350
+ repr(value)
1351
+ .replace("inf", _INFSTR)
1352
+ .replace("nan", f"({_INFSTR}-{_INFSTR})")
1353
+ )
1354
+ else:
1355
+ self.write(repr(value))
1356
+
1357
+ def visit_Constant(self, node):
1358
+ value = node.value
1359
+ if isinstance(value, tuple):
1360
+ with self.delimit("(", ")"):
1361
+ self.items_view(self._write_constant, value)
1362
+ elif value is ...:
1363
+ self.write("...")
1364
+ else:
1365
+ if node.kind == "u":
1366
+ self.write("u")
1367
+ self._write_constant(node.value)
1368
+
1369
+ def visit_List(self, node):
1370
+ with self.delimit("[", "]"):
1371
+ self.interleave(lambda: self.write(", "), self.traverse, node.elts)
1372
+
1373
+ def visit_ListComp(self, node):
1374
+ with self.delimit("[", "]"):
1375
+ self.traverse(node.elt)
1376
+ for gen in node.generators:
1377
+ self.traverse(gen)
1378
+
1379
+ def visit_GeneratorExp(self, node):
1380
+ with self.delimit("(", ")"):
1381
+ self.traverse(node.elt)
1382
+ for gen in node.generators:
1383
+ self.traverse(gen)
1384
+
1385
+ def visit_SetComp(self, node):
1386
+ with self.delimit("{", "}"):
1387
+ self.traverse(node.elt)
1388
+ for gen in node.generators:
1389
+ self.traverse(gen)
1390
+
1391
+ def visit_DictComp(self, node):
1392
+ with self.delimit("{", "}"):
1393
+ self.traverse(node.key)
1394
+ self.write(": ")
1395
+ self.traverse(node.value)
1396
+ for gen in node.generators:
1397
+ self.traverse(gen)
1398
+
1399
+ def visit_comprehension(self, node):
1400
+ if node.is_async:
1401
+ self.write(" async for ")
1402
+ else:
1403
+ self.write(" for ")
1404
+ self.set_precedence(_Precedence.TUPLE, node.target)
1405
+ self.traverse(node.target)
1406
+ self.write(" in ")
1407
+ self.set_precedence(_Precedence.TEST.next(), node.iter, *node.ifs)
1408
+ self.traverse(node.iter)
1409
+ for if_clause in node.ifs:
1410
+ self.write(" if ")
1411
+ self.traverse(if_clause)
1412
+
1413
+ def visit_IfExp(self, node):
1414
+ with self.require_parens(_Precedence.TEST, node):
1415
+ self.set_precedence(_Precedence.TEST.next(), node.body, node.test)
1416
+ self.traverse(node.body)
1417
+ self.write(" if ")
1418
+ self.traverse(node.test)
1419
+ self.write(" else ")
1420
+ self.set_precedence(_Precedence.TEST, node.orelse)
1421
+ self.traverse(node.orelse)
1422
+
1423
+ def visit_Set(self, node):
1424
+ if node.elts:
1425
+ with self.delimit("{", "}"):
1426
+ self.interleave(lambda: self.write(", "), self.traverse, node.elts)
1427
+ else:
1428
+ # `{}` would be interpreted as a dictionary literal, and
1429
+ # `set` might be shadowed. Thus:
1430
+ self.write('{*()}')
1431
+
1432
+ def visit_Dict(self, node):
1433
+ def write_key_value_pair(k, v):
1434
+ self.traverse(k)
1435
+ self.write(": ")
1436
+ self.traverse(v)
1437
+
1438
+ def write_item(item):
1439
+ k, v = item
1440
+ if k is None:
1441
+ # for dictionary unpacking operator in dicts {**{'y': 2}}
1442
+ # see PEP 448 for details
1443
+ self.write("**")
1444
+ self.set_precedence(_Precedence.EXPR, v)
1445
+ self.traverse(v)
1446
+ else:
1447
+ write_key_value_pair(k, v)
1448
+
1449
+ with self.delimit("{", "}"):
1450
+ self.interleave(
1451
+ lambda: self.write(", "), write_item, zip(node.keys, node.values)
1452
+ )
1453
+
1454
+ def visit_Tuple(self, node):
1455
+ with self.delimit_if(
1456
+ "(",
1457
+ ")",
1458
+ len(node.elts) == 0 or self.get_precedence(node) > _Precedence.TUPLE
1459
+ ):
1460
+ self.items_view(self.traverse, node.elts)
1461
+
1462
+ unop = {"Invert": "~", "Not": "not", "UAdd": "+", "USub": "-"}
1463
+ unop_precedence = {
1464
+ "not": _Precedence.NOT,
1465
+ "~": _Precedence.FACTOR,
1466
+ "+": _Precedence.FACTOR,
1467
+ "-": _Precedence.FACTOR,
1468
+ }
1469
+
1470
+ def visit_UnaryOp(self, node):
1471
+ operator = self.unop[node.op.__class__.__name__]
1472
+ operator_precedence = self.unop_precedence[operator]
1473
+ with self.require_parens(operator_precedence, node):
1474
+ self.write(operator)
1475
+ # factor prefixes (+, -, ~) shouldn't be separated
1476
+ # from the value they belong, (e.g: +1 instead of + 1)
1477
+ if operator_precedence is not _Precedence.FACTOR:
1478
+ self.write(" ")
1479
+ self.set_precedence(operator_precedence, node.operand)
1480
+ self.traverse(node.operand)
1481
+
1482
+ binop = {
1483
+ "Add": "+",
1484
+ "Sub": "-",
1485
+ "Mult": "*",
1486
+ "MatMult": "@",
1487
+ "Div": "/",
1488
+ "Mod": "%",
1489
+ "LShift": "<<",
1490
+ "RShift": ">>",
1491
+ "BitOr": "|",
1492
+ "BitXor": "^",
1493
+ "BitAnd": "&",
1494
+ "FloorDiv": "//",
1495
+ "Pow": "**",
1496
+ }
1497
+
1498
+ binop_precedence = {
1499
+ "+": _Precedence.ARITH,
1500
+ "-": _Precedence.ARITH,
1501
+ "*": _Precedence.TERM,
1502
+ "@": _Precedence.TERM,
1503
+ "/": _Precedence.TERM,
1504
+ "%": _Precedence.TERM,
1505
+ "<<": _Precedence.SHIFT,
1506
+ ">>": _Precedence.SHIFT,
1507
+ "|": _Precedence.BOR,
1508
+ "^": _Precedence.BXOR,
1509
+ "&": _Precedence.BAND,
1510
+ "//": _Precedence.TERM,
1511
+ "**": _Precedence.POWER,
1512
+ }
1513
+
1514
+ binop_rassoc = frozenset(("**",))
1515
+ def visit_BinOp(self, node):
1516
+ operator = self.binop[node.op.__class__.__name__]
1517
+ operator_precedence = self.binop_precedence[operator]
1518
+ with self.require_parens(operator_precedence, node):
1519
+ if operator in self.binop_rassoc:
1520
+ left_precedence = operator_precedence.next()
1521
+ right_precedence = operator_precedence
1522
+ else:
1523
+ left_precedence = operator_precedence
1524
+ right_precedence = operator_precedence.next()
1525
+
1526
+ self.set_precedence(left_precedence, node.left)
1527
+ self.traverse(node.left)
1528
+ self.write(f" {operator} ")
1529
+ self.set_precedence(right_precedence, node.right)
1530
+ self.traverse(node.right)
1531
+
1532
+ cmpops = {
1533
+ "Eq": "==",
1534
+ "NotEq": "!=",
1535
+ "Lt": "<",
1536
+ "LtE": "<=",
1537
+ "Gt": ">",
1538
+ "GtE": ">=",
1539
+ "Is": "is",
1540
+ "IsNot": "is not",
1541
+ "In": "in",
1542
+ "NotIn": "not in",
1543
+ }
1544
+
1545
+ def visit_Compare(self, node):
1546
+ with self.require_parens(_Precedence.CMP, node):
1547
+ self.set_precedence(_Precedence.CMP.next(), node.left, *node.comparators)
1548
+ self.traverse(node.left)
1549
+ for o, e in zip(node.ops, node.comparators):
1550
+ self.write(" " + self.cmpops[o.__class__.__name__] + " ")
1551
+ self.traverse(e)
1552
+
1553
+ boolops = {"And": "and", "Or": "or"}
1554
+ boolop_precedence = {"and": _Precedence.AND, "or": _Precedence.OR}
1555
+
1556
+ def visit_BoolOp(self, node):
1557
+ operator = self.boolops[node.op.__class__.__name__]
1558
+ operator_precedence = self.boolop_precedence[operator]
1559
+
1560
+ def increasing_level_traverse(node):
1561
+ nonlocal operator_precedence
1562
+ operator_precedence = operator_precedence.next()
1563
+ self.set_precedence(operator_precedence, node)
1564
+ self.traverse(node)
1565
+
1566
+ with self.require_parens(operator_precedence, node):
1567
+ s = f" {operator} "
1568
+ self.interleave(lambda: self.write(s), increasing_level_traverse, node.values)
1569
+
1570
+ def visit_Attribute(self, node):
1571
+ self.set_precedence(_Precedence.ATOM, node.value)
1572
+ self.traverse(node.value)
1573
+ # Special case: 3.__abs__() is a syntax error, so if node.value
1574
+ # is an integer literal then we need to either parenthesize
1575
+ # it or add an extra space to get 3 .__abs__().
1576
+ if isinstance(node.value, Constant) and isinstance(node.value.value, int):
1577
+ self.write(" ")
1578
+ self.write(".")
1579
+ self.write(node.attr)
1580
+
1581
+ def visit_Call(self, node):
1582
+ self.set_precedence(_Precedence.ATOM, node.func)
1583
+ self.traverse(node.func)
1584
+ with self.delimit("(", ")"):
1585
+ comma = False
1586
+ for e in node.args:
1587
+ if comma:
1588
+ self.write(", ")
1589
+ else:
1590
+ comma = True
1591
+ self.traverse(e)
1592
+ for e in node.keywords:
1593
+ if comma:
1594
+ self.write(", ")
1595
+ else:
1596
+ comma = True
1597
+ self.traverse(e)
1598
+
1599
+ def visit_Subscript(self, node):
1600
+ def is_non_empty_tuple(slice_value):
1601
+ return (
1602
+ isinstance(slice_value, Tuple)
1603
+ and slice_value.elts
1604
+ )
1605
+
1606
+ self.set_precedence(_Precedence.ATOM, node.value)
1607
+ self.traverse(node.value)
1608
+ with self.delimit("[", "]"):
1609
+ if is_non_empty_tuple(node.slice):
1610
+ # parentheses can be omitted if the tuple isn't empty
1611
+ self.items_view(self.traverse, node.slice.elts)
1612
+ else:
1613
+ self.traverse(node.slice)
1614
+
1615
+ def visit_Starred(self, node):
1616
+ self.write("*")
1617
+ self.set_precedence(_Precedence.EXPR, node.value)
1618
+ self.traverse(node.value)
1619
+
1620
+ def visit_Ellipsis(self, node):
1621
+ self.write("...")
1622
+
1623
+ def visit_Slice(self, node):
1624
+ if node.lower:
1625
+ self.traverse(node.lower)
1626
+ self.write(":")
1627
+ if node.upper:
1628
+ self.traverse(node.upper)
1629
+ if node.step:
1630
+ self.write(":")
1631
+ self.traverse(node.step)
1632
+
1633
+ def visit_Match(self, node):
1634
+ self.fill("match ")
1635
+ self.traverse(node.subject)
1636
+ with self.block():
1637
+ for case in node.cases:
1638
+ self.traverse(case)
1639
+
1640
+ def visit_arg(self, node):
1641
+ self.write(node.arg)
1642
+ if node.annotation:
1643
+ self.write(": ")
1644
+ self.traverse(node.annotation)
1645
+
1646
+ def visit_arguments(self, node):
1647
+ first = True
1648
+ # normal arguments
1649
+ all_args = node.posonlyargs + node.args
1650
+ defaults = [None] * (len(all_args) - len(node.defaults)) + node.defaults
1651
+ for index, elements in enumerate(zip(all_args, defaults), 1):
1652
+ a, d = elements
1653
+ if first:
1654
+ first = False
1655
+ else:
1656
+ self.write(", ")
1657
+ self.traverse(a)
1658
+ if d:
1659
+ self.write("=")
1660
+ self.traverse(d)
1661
+ if index == len(node.posonlyargs):
1662
+ self.write(", /")
1663
+
1664
+ # varargs, or bare '*' if no varargs but keyword-only arguments present
1665
+ if node.vararg or node.kwonlyargs:
1666
+ if first:
1667
+ first = False
1668
+ else:
1669
+ self.write(", ")
1670
+ self.write("*")
1671
+ if node.vararg:
1672
+ self.write(node.vararg.arg)
1673
+ if node.vararg.annotation:
1674
+ self.write(": ")
1675
+ self.traverse(node.vararg.annotation)
1676
+
1677
+ # keyword-only arguments
1678
+ if node.kwonlyargs:
1679
+ for a, d in zip(node.kwonlyargs, node.kw_defaults):
1680
+ self.write(", ")
1681
+ self.traverse(a)
1682
+ if d:
1683
+ self.write("=")
1684
+ self.traverse(d)
1685
+
1686
+ # kwargs
1687
+ if node.kwarg:
1688
+ if first:
1689
+ first = False
1690
+ else:
1691
+ self.write(", ")
1692
+ self.write("**" + node.kwarg.arg)
1693
+ if node.kwarg.annotation:
1694
+ self.write(": ")
1695
+ self.traverse(node.kwarg.annotation)
1696
+
1697
+ def visit_keyword(self, node):
1698
+ if node.arg is None:
1699
+ self.write("**")
1700
+ else:
1701
+ self.write(node.arg)
1702
+ self.write("=")
1703
+ self.traverse(node.value)
1704
+
1705
+ def visit_Lambda(self, node):
1706
+ with self.require_parens(_Precedence.TEST, node):
1707
+ self.write("lambda")
1708
+ with self.buffered() as buffer:
1709
+ self.traverse(node.args)
1710
+ if buffer:
1711
+ self.write(" ", *buffer)
1712
+ self.write(": ")
1713
+ self.set_precedence(_Precedence.TEST, node.body)
1714
+ self.traverse(node.body)
1715
+
1716
+ def visit_alias(self, node):
1717
+ self.write(node.name)
1718
+ if node.asname:
1719
+ self.write(" as " + node.asname)
1720
+
1721
+ def visit_withitem(self, node):
1722
+ self.traverse(node.context_expr)
1723
+ if node.optional_vars:
1724
+ self.write(" as ")
1725
+ self.traverse(node.optional_vars)
1726
+
1727
+ def visit_match_case(self, node):
1728
+ self.fill("case ")
1729
+ self.traverse(node.pattern)
1730
+ if node.guard:
1731
+ self.write(" if ")
1732
+ self.traverse(node.guard)
1733
+ with self.block():
1734
+ self.traverse(node.body)
1735
+
1736
+ def visit_MatchValue(self, node):
1737
+ self.traverse(node.value)
1738
+
1739
+ def visit_MatchSingleton(self, node):
1740
+ self._write_constant(node.value)
1741
+
1742
+ def visit_MatchSequence(self, node):
1743
+ with self.delimit("[", "]"):
1744
+ self.interleave(
1745
+ lambda: self.write(", "), self.traverse, node.patterns
1746
+ )
1747
+
1748
+ def visit_MatchStar(self, node):
1749
+ name = node.name
1750
+ if name is None:
1751
+ name = "_"
1752
+ self.write(f"*{name}")
1753
+
1754
+ def visit_MatchMapping(self, node):
1755
+ def write_key_pattern_pair(pair):
1756
+ k, p = pair
1757
+ self.traverse(k)
1758
+ self.write(": ")
1759
+ self.traverse(p)
1760
+
1761
+ with self.delimit("{", "}"):
1762
+ keys = node.keys
1763
+ self.interleave(
1764
+ lambda: self.write(", "),
1765
+ write_key_pattern_pair,
1766
+ zip(keys, node.patterns, strict=True),
1767
+ )
1768
+ rest = node.rest
1769
+ if rest is not None:
1770
+ if keys:
1771
+ self.write(", ")
1772
+ self.write(f"**{rest}")
1773
+
1774
+ def visit_MatchClass(self, node):
1775
+ self.set_precedence(_Precedence.ATOM, node.cls)
1776
+ self.traverse(node.cls)
1777
+ with self.delimit("(", ")"):
1778
+ patterns = node.patterns
1779
+ self.interleave(
1780
+ lambda: self.write(", "), self.traverse, patterns
1781
+ )
1782
+ attrs = node.kwd_attrs
1783
+ if attrs:
1784
+ def write_attr_pattern(pair):
1785
+ attr, pattern = pair
1786
+ self.write(f"{attr}=")
1787
+ self.traverse(pattern)
1788
+
1789
+ if patterns:
1790
+ self.write(", ")
1791
+ self.interleave(
1792
+ lambda: self.write(", "),
1793
+ write_attr_pattern,
1794
+ zip(attrs, node.kwd_patterns, strict=True),
1795
+ )
1796
+
1797
+ def visit_MatchAs(self, node):
1798
+ name = node.name
1799
+ pattern = node.pattern
1800
+ if name is None:
1801
+ self.write("_")
1802
+ elif pattern is None:
1803
+ self.write(node.name)
1804
+ else:
1805
+ with self.require_parens(_Precedence.TEST, node):
1806
+ self.set_precedence(_Precedence.BOR, node.pattern)
1807
+ self.traverse(node.pattern)
1808
+ self.write(f" as {node.name}")
1809
+
1810
+ def visit_MatchOr(self, node):
1811
+ with self.require_parens(_Precedence.BOR, node):
1812
+ self.set_precedence(_Precedence.BOR.next(), *node.patterns)
1813
+ self.interleave(lambda: self.write(" | "), self.traverse, node.patterns)
1814
+
1815
+ def unparse(ast_obj):
1816
+ unparser = _Unparser()
1817
+ return unparser.visit(ast_obj)
1818
+
1819
+
1820
+ _deprecated_globals = {
1821
+ name: globals().pop(name)
1822
+ for name in ('Num', 'Str', 'Bytes', 'NameConstant', 'Ellipsis')
1823
+ }
1824
+
1825
+ def __getattr__(name):
1826
+ if name in _deprecated_globals:
1827
+ globals()[name] = value = _deprecated_globals[name]
1828
+ import warnings
1829
+ warnings._deprecated(
1830
+ f"ast.{name}", message=_DEPRECATED_CLASS_MESSAGE, remove=(3, 14)
1831
+ )
1832
+ return value
1833
+ raise AttributeError(f"module 'ast' has no attribute '{name}'")
1834
+
1835
+
1836
+ def main():
1837
+ import argparse
1838
+
1839
+ parser = argparse.ArgumentParser(prog='python -m ast')
1840
+ parser.add_argument('infile', nargs='?', default='-',
1841
+ help='the file to parse; defaults to stdin')
1842
+ parser.add_argument('-m', '--mode', default='exec',
1843
+ choices=('exec', 'single', 'eval', 'func_type'),
1844
+ help='specify what kind of code must be parsed')
1845
+ parser.add_argument('--no-type-comments', default=True, action='store_false',
1846
+ help="don't add information about type comments")
1847
+ parser.add_argument('-a', '--include-attributes', action='store_true',
1848
+ help='include attributes such as line numbers and '
1849
+ 'column offsets')
1850
+ parser.add_argument('-i', '--indent', type=int, default=3,
1851
+ help='indentation of nodes (number of spaces)')
1852
+ args = parser.parse_args()
1853
+
1854
+ if args.infile == '-':
1855
+ name = '<stdin>'
1856
+ source = sys.stdin.buffer.read()
1857
+ else:
1858
+ name = args.infile
1859
+ with open(args.infile, 'rb') as infile:
1860
+ source = infile.read()
1861
+ tree = parse(source, name, args.mode, type_comments=args.no_type_comments)
1862
+ print(dump(tree, include_attributes=args.include_attributes, indent=args.indent))
1863
+
1864
+ if __name__ == '__main__':
1865
+ main()