@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,3479 @@
1
+ """Get useful information from live Python objects.
2
+
3
+ This module encapsulates the interface provided by the internal special
4
+ attributes (co_*, tb_*, etc.) in a friendlier fashion.
5
+ It also provides some help for examining source code and class layout.
6
+
7
+ Here are some of the useful functions provided by this module:
8
+
9
+ ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
10
+ isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
11
+ isroutine() - check object types
12
+ getmembers() - get members of an object that satisfy a given condition
13
+
14
+ getfile(), getsourcefile(), getsource() - find an object's source code
15
+ getdoc(), getcomments() - get documentation on an object
16
+ getmodule() - determine the module that an object came from
17
+ getclasstree() - arrange classes so as to represent their hierarchy
18
+
19
+ getargvalues(), getcallargs() - get info about function arguments
20
+ getfullargspec() - same, with support for Python 3 features
21
+ formatargvalues() - format an argument spec
22
+ getouterframes(), getinnerframes() - get info about frames
23
+ currentframe() - get the current stack frame
24
+ stack(), trace() - get info about frames on the stack or in a traceback
25
+
26
+ signature() - get a Signature object for the callable
27
+
28
+ get_annotations() - safely compute an object's annotations
29
+ """
30
+
31
+ # This module is in the public domain. No warranties.
32
+
33
+ __author__ = ('Ka-Ping Yee <ping@lfw.org>',
34
+ 'Yury Selivanov <yselivanov@sprymix.com>')
35
+
36
+ __all__ = [
37
+ "AGEN_CLOSED",
38
+ "AGEN_CREATED",
39
+ "AGEN_RUNNING",
40
+ "AGEN_SUSPENDED",
41
+ "ArgInfo",
42
+ "Arguments",
43
+ "Attribute",
44
+ "BlockFinder",
45
+ "BoundArguments",
46
+ "BufferFlags",
47
+ "CORO_CLOSED",
48
+ "CORO_CREATED",
49
+ "CORO_RUNNING",
50
+ "CORO_SUSPENDED",
51
+ "CO_ASYNC_GENERATOR",
52
+ "CO_COROUTINE",
53
+ "CO_GENERATOR",
54
+ "CO_ITERABLE_COROUTINE",
55
+ "CO_NESTED",
56
+ "CO_NEWLOCALS",
57
+ "CO_NOFREE",
58
+ "CO_OPTIMIZED",
59
+ "CO_VARARGS",
60
+ "CO_VARKEYWORDS",
61
+ "ClassFoundException",
62
+ "ClosureVars",
63
+ "EndOfBlock",
64
+ "FrameInfo",
65
+ "FullArgSpec",
66
+ "GEN_CLOSED",
67
+ "GEN_CREATED",
68
+ "GEN_RUNNING",
69
+ "GEN_SUSPENDED",
70
+ "Parameter",
71
+ "Signature",
72
+ "TPFLAGS_IS_ABSTRACT",
73
+ "Traceback",
74
+ "classify_class_attrs",
75
+ "cleandoc",
76
+ "currentframe",
77
+ "findsource",
78
+ "formatannotation",
79
+ "formatannotationrelativeto",
80
+ "formatargvalues",
81
+ "get_annotations",
82
+ "getabsfile",
83
+ "getargs",
84
+ "getargvalues",
85
+ "getasyncgenlocals",
86
+ "getasyncgenstate",
87
+ "getattr_static",
88
+ "getblock",
89
+ "getcallargs",
90
+ "getclasstree",
91
+ "getclosurevars",
92
+ "getcomments",
93
+ "getcoroutinelocals",
94
+ "getcoroutinestate",
95
+ "getdoc",
96
+ "getfile",
97
+ "getframeinfo",
98
+ "getfullargspec",
99
+ "getgeneratorlocals",
100
+ "getgeneratorstate",
101
+ "getinnerframes",
102
+ "getlineno",
103
+ "getmembers",
104
+ "getmembers_static",
105
+ "getmodule",
106
+ "getmodulename",
107
+ "getmro",
108
+ "getouterframes",
109
+ "getsource",
110
+ "getsourcefile",
111
+ "getsourcelines",
112
+ "indentsize",
113
+ "isabstract",
114
+ "isasyncgen",
115
+ "isasyncgenfunction",
116
+ "isawaitable",
117
+ "isbuiltin",
118
+ "isclass",
119
+ "iscode",
120
+ "iscoroutine",
121
+ "iscoroutinefunction",
122
+ "isdatadescriptor",
123
+ "isframe",
124
+ "isfunction",
125
+ "isgenerator",
126
+ "isgeneratorfunction",
127
+ "isgetsetdescriptor",
128
+ "ismemberdescriptor",
129
+ "ismethod",
130
+ "ismethoddescriptor",
131
+ "ismethodwrapper",
132
+ "ismodule",
133
+ "isroutine",
134
+ "istraceback",
135
+ "markcoroutinefunction",
136
+ "signature",
137
+ "stack",
138
+ "trace",
139
+ "unwrap",
140
+ "walktree",
141
+ ]
142
+
143
+
144
+ import abc
145
+ import ast
146
+ import dis
147
+ import collections.abc
148
+ import enum
149
+ import importlib.machinery
150
+ import itertools
151
+ import linecache
152
+ import os
153
+ import re
154
+ import sys
155
+ import tokenize
156
+ import token
157
+ import types
158
+ import functools
159
+ import builtins
160
+ from keyword import iskeyword
161
+ from operator import attrgetter
162
+ from collections import namedtuple, OrderedDict
163
+ from typing import _rewrite_star_unpack
164
+ from weakref import ref as make_weakref
165
+
166
+ # Create constants for the compiler flags in Include/code.h
167
+ # We try to get them from dis to avoid duplication
168
+ mod_dict = globals()
169
+ for k, v in dis.COMPILER_FLAG_NAMES.items():
170
+ mod_dict["CO_" + v] = k
171
+ del k, v, mod_dict
172
+
173
+ # See Include/object.h
174
+ TPFLAGS_IS_ABSTRACT = 1 << 20
175
+
176
+
177
+ def get_annotations(obj, *, globals=None, locals=None, eval_str=False):
178
+ """Compute the annotations dict for an object.
179
+
180
+ obj may be a callable, class, or module.
181
+ Passing in an object of any other type raises TypeError.
182
+
183
+ Returns a dict. get_annotations() returns a new dict every time
184
+ it's called; calling it twice on the same object will return two
185
+ different but equivalent dicts.
186
+
187
+ This function handles several details for you:
188
+
189
+ * If eval_str is true, values of type str will
190
+ be un-stringized using eval(). This is intended
191
+ for use with stringized annotations
192
+ ("from __future__ import annotations").
193
+ * If obj doesn't have an annotations dict, returns an
194
+ empty dict. (Functions and methods always have an
195
+ annotations dict; classes, modules, and other types of
196
+ callables may not.)
197
+ * Ignores inherited annotations on classes. If a class
198
+ doesn't have its own annotations dict, returns an empty dict.
199
+ * All accesses to object members and dict values are done
200
+ using getattr() and dict.get() for safety.
201
+ * Always, always, always returns a freshly-created dict.
202
+
203
+ eval_str controls whether or not values of type str are replaced
204
+ with the result of calling eval() on those values:
205
+
206
+ * If eval_str is true, eval() is called on values of type str.
207
+ * If eval_str is false (the default), values of type str are unchanged.
208
+
209
+ globals and locals are passed in to eval(); see the documentation
210
+ for eval() for more information. If either globals or locals is
211
+ None, this function may replace that value with a context-specific
212
+ default, contingent on type(obj):
213
+
214
+ * If obj is a module, globals defaults to obj.__dict__.
215
+ * If obj is a class, globals defaults to
216
+ sys.modules[obj.__module__].__dict__ and locals
217
+ defaults to the obj class namespace.
218
+ * If obj is a callable, globals defaults to obj.__globals__,
219
+ although if obj is a wrapped function (using
220
+ functools.update_wrapper()) it is first unwrapped.
221
+ """
222
+ if isinstance(obj, type):
223
+ # class
224
+ obj_dict = getattr(obj, '__dict__', None)
225
+ if obj_dict and hasattr(obj_dict, 'get'):
226
+ ann = obj_dict.get('__annotations__', None)
227
+ if isinstance(ann, types.GetSetDescriptorType):
228
+ ann = None
229
+ else:
230
+ ann = None
231
+
232
+ obj_globals = None
233
+ module_name = getattr(obj, '__module__', None)
234
+ if module_name:
235
+ module = sys.modules.get(module_name, None)
236
+ if module:
237
+ obj_globals = getattr(module, '__dict__', None)
238
+ obj_locals = dict(vars(obj))
239
+ unwrap = obj
240
+ elif isinstance(obj, types.ModuleType):
241
+ # module
242
+ ann = getattr(obj, '__annotations__', None)
243
+ obj_globals = getattr(obj, '__dict__')
244
+ obj_locals = None
245
+ unwrap = None
246
+ elif callable(obj):
247
+ # this includes types.Function, types.BuiltinFunctionType,
248
+ # types.BuiltinMethodType, functools.partial, functools.singledispatch,
249
+ # "class funclike" from Lib/test/test_inspect... on and on it goes.
250
+ ann = getattr(obj, '__annotations__', None)
251
+ obj_globals = getattr(obj, '__globals__', None)
252
+ obj_locals = None
253
+ unwrap = obj
254
+ else:
255
+ raise TypeError(f"{obj!r} is not a module, class, or callable.")
256
+
257
+ if ann is None:
258
+ return {}
259
+
260
+ if not isinstance(ann, dict):
261
+ raise ValueError(f"{obj!r}.__annotations__ is neither a dict nor None")
262
+
263
+ if not ann:
264
+ return {}
265
+
266
+ if not eval_str:
267
+ return dict(ann)
268
+
269
+ if unwrap is not None:
270
+ while True:
271
+ if hasattr(unwrap, '__wrapped__'):
272
+ unwrap = unwrap.__wrapped__
273
+ continue
274
+ if isinstance(unwrap, functools.partial):
275
+ unwrap = unwrap.func
276
+ continue
277
+ break
278
+ if hasattr(unwrap, "__globals__"):
279
+ obj_globals = unwrap.__globals__
280
+
281
+ if globals is None:
282
+ globals = obj_globals
283
+ if locals is None:
284
+ locals = obj_locals or {}
285
+
286
+ # "Inject" type parameters into the local namespace
287
+ # (unless they are shadowed by assignments *in* the local namespace),
288
+ # as a way of emulating annotation scopes when calling `eval()`
289
+ if type_params := getattr(obj, "__type_params__", ()):
290
+ locals = {param.__name__: param for param in type_params} | locals
291
+
292
+ return_value = {
293
+ key: value if not isinstance(value, str)
294
+ else eval(_rewrite_star_unpack(value), globals, locals)
295
+ for key, value in ann.items() }
296
+ return return_value
297
+
298
+
299
+ # ----------------------------------------------------------- type-checking
300
+ def ismodule(object):
301
+ """Return true if the object is a module."""
302
+ return isinstance(object, types.ModuleType)
303
+
304
+ def isclass(object):
305
+ """Return true if the object is a class."""
306
+ return isinstance(object, type)
307
+
308
+ def ismethod(object):
309
+ """Return true if the object is an instance method."""
310
+ return isinstance(object, types.MethodType)
311
+
312
+ def ismethoddescriptor(object):
313
+ """Return true if the object is a method descriptor.
314
+
315
+ But not if ismethod(), isclass() or isfunction() is true.
316
+
317
+ An object passing this test (for example, int.__add__) has a __get__
318
+ attribute, but not a __set__ attribute or a __delete__ attribute.
319
+ Beyond that, the set of attributes varies; __name__ is usually
320
+ sensible, and __doc__ often is.
321
+
322
+ Methods implemented via descriptors that also pass one of the other
323
+ tests (ismethod(), isclass(), isfunction()) make this function return
324
+ false, simply because those other tests promise more -- you can, for
325
+ example, count on having the __func__ attribute when an object passes
326
+ ismethod()."""
327
+ if isclass(object) or ismethod(object) or isfunction(object):
328
+ # mutual exclusion
329
+ return False
330
+ if isinstance(object, functools.partial):
331
+ # Lie for children. The addition of partial.__get__
332
+ # doesn't currently change the partial objects behaviour,
333
+ # not counting a warning about future changes.
334
+ return False
335
+ tp = type(object)
336
+ return (hasattr(tp, "__get__")
337
+ and not hasattr(tp, "__set__")
338
+ and not hasattr(tp, "__delete__"))
339
+
340
+ def isdatadescriptor(object):
341
+ """Return true if the object is a data descriptor.
342
+
343
+ But not if ismethod(), isclass() or isfunction() is true.
344
+
345
+ Data descriptors have a __set__ or a __delete__ attribute. Examples are
346
+ properties, getsets, and members. For the latter two (defined only in C
347
+ extension modules) more specific tests are available as well:
348
+ isgetsetdescriptor() and ismemberdescriptor(), respectively.
349
+
350
+ Typically, data descriptors will also have __name__ and __doc__ attributes
351
+ (properties, getsets, and members have both of these attributes), but this
352
+ is not guaranteed."""
353
+ if isclass(object) or ismethod(object) or isfunction(object):
354
+ # mutual exclusion
355
+ return False
356
+ tp = type(object)
357
+ return hasattr(tp, "__set__") or hasattr(tp, "__delete__")
358
+
359
+ if hasattr(types, 'MemberDescriptorType'):
360
+ # CPython and equivalent
361
+ def ismemberdescriptor(object):
362
+ """Return true if the object is a member descriptor.
363
+
364
+ Member descriptors are specialized descriptors defined in extension
365
+ modules."""
366
+ return isinstance(object, types.MemberDescriptorType)
367
+ else:
368
+ # Other implementations
369
+ def ismemberdescriptor(object):
370
+ """Return true if the object is a member descriptor.
371
+
372
+ Member descriptors are specialized descriptors defined in extension
373
+ modules."""
374
+ return False
375
+
376
+ if hasattr(types, 'GetSetDescriptorType'):
377
+ # CPython and equivalent
378
+ def isgetsetdescriptor(object):
379
+ """Return true if the object is a getset descriptor.
380
+
381
+ getset descriptors are specialized descriptors defined in extension
382
+ modules."""
383
+ return isinstance(object, types.GetSetDescriptorType)
384
+ else:
385
+ # Other implementations
386
+ def isgetsetdescriptor(object):
387
+ """Return true if the object is a getset descriptor.
388
+
389
+ getset descriptors are specialized descriptors defined in extension
390
+ modules."""
391
+ return False
392
+
393
+ def isfunction(object):
394
+ """Return true if the object is a user-defined function.
395
+
396
+ Function objects provide these attributes:
397
+ __doc__ documentation string
398
+ __name__ name with which this function was defined
399
+ __code__ code object containing compiled function bytecode
400
+ __defaults__ tuple of any default values for arguments
401
+ __globals__ global namespace in which this function was defined
402
+ __annotations__ dict of parameter annotations
403
+ __kwdefaults__ dict of keyword only parameters with defaults"""
404
+ return isinstance(object, types.FunctionType)
405
+
406
+ def _has_code_flag(f, flag):
407
+ """Return true if ``f`` is a function (or a method or functools.partial
408
+ wrapper wrapping a function or a functools.partialmethod wrapping a
409
+ function) whose code object has the given ``flag``
410
+ set in its flags."""
411
+ f = functools._unwrap_partialmethod(f)
412
+ while ismethod(f):
413
+ f = f.__func__
414
+ f = functools._unwrap_partial(f)
415
+ if not (isfunction(f) or _signature_is_functionlike(f)):
416
+ return False
417
+ return bool(f.__code__.co_flags & flag)
418
+
419
+ def isgeneratorfunction(obj):
420
+ """Return true if the object is a user-defined generator function.
421
+
422
+ Generator function objects provide the same attributes as functions.
423
+ See help(isfunction) for a list of attributes."""
424
+ return _has_code_flag(obj, CO_GENERATOR)
425
+
426
+ # A marker for markcoroutinefunction and iscoroutinefunction.
427
+ _is_coroutine_mark = object()
428
+
429
+ def _has_coroutine_mark(f):
430
+ while ismethod(f):
431
+ f = f.__func__
432
+ f = functools._unwrap_partial(f)
433
+ return getattr(f, "_is_coroutine_marker", None) is _is_coroutine_mark
434
+
435
+ def markcoroutinefunction(func):
436
+ """
437
+ Decorator to ensure callable is recognised as a coroutine function.
438
+ """
439
+ if hasattr(func, '__func__'):
440
+ func = func.__func__
441
+ func._is_coroutine_marker = _is_coroutine_mark
442
+ return func
443
+
444
+ def iscoroutinefunction(obj):
445
+ """Return true if the object is a coroutine function.
446
+
447
+ Coroutine functions are normally defined with "async def" syntax, but may
448
+ be marked via markcoroutinefunction.
449
+ """
450
+ return _has_code_flag(obj, CO_COROUTINE) or _has_coroutine_mark(obj)
451
+
452
+ def isasyncgenfunction(obj):
453
+ """Return true if the object is an asynchronous generator function.
454
+
455
+ Asynchronous generator functions are defined with "async def"
456
+ syntax and have "yield" expressions in their body.
457
+ """
458
+ return _has_code_flag(obj, CO_ASYNC_GENERATOR)
459
+
460
+ def isasyncgen(object):
461
+ """Return true if the object is an asynchronous generator."""
462
+ return isinstance(object, types.AsyncGeneratorType)
463
+
464
+ def isgenerator(object):
465
+ """Return true if the object is a generator.
466
+
467
+ Generator objects provide these attributes:
468
+ __iter__ defined to support iteration over container
469
+ close raises a new GeneratorExit exception inside the
470
+ generator to terminate the iteration
471
+ gi_code code object
472
+ gi_frame frame object or possibly None once the generator has
473
+ been exhausted
474
+ gi_running set to 1 when generator is executing, 0 otherwise
475
+ gi_suspended set to 1 when the generator is suspended at a yield point, 0 otherwise
476
+ gi_yieldfrom object being iterated by yield from or None
477
+ next return the next item from the container
478
+ send resumes the generator and "sends" a value that becomes
479
+ the result of the current yield-expression
480
+ throw used to raise an exception inside the generator"""
481
+ return isinstance(object, types.GeneratorType)
482
+
483
+ def iscoroutine(object):
484
+ """Return true if the object is a coroutine."""
485
+ return isinstance(object, types.CoroutineType)
486
+
487
+ def isawaitable(object):
488
+ """Return true if object can be passed to an ``await`` expression."""
489
+ return (isinstance(object, types.CoroutineType) or
490
+ isinstance(object, types.GeneratorType) and
491
+ bool(object.gi_code.co_flags & CO_ITERABLE_COROUTINE) or
492
+ isinstance(object, collections.abc.Awaitable))
493
+
494
+ def istraceback(object):
495
+ """Return true if the object is a traceback.
496
+
497
+ Traceback objects provide these attributes:
498
+ tb_frame frame object at this level
499
+ tb_lasti index of last attempted instruction in bytecode
500
+ tb_lineno current line number in Python source code
501
+ tb_next next inner traceback object (called by this level)"""
502
+ return isinstance(object, types.TracebackType)
503
+
504
+ def isframe(object):
505
+ """Return true if the object is a frame object.
506
+
507
+ Frame objects provide these attributes:
508
+ f_back next outer frame object (this frame's caller)
509
+ f_builtins built-in namespace seen by this frame
510
+ f_code code object being executed in this frame
511
+ f_globals global namespace seen by this frame
512
+ f_lasti index of last attempted instruction in bytecode
513
+ f_lineno current line number in Python source code
514
+ f_locals local namespace seen by this frame
515
+ f_trace tracing function for this frame, or None"""
516
+ return isinstance(object, types.FrameType)
517
+
518
+ def iscode(object):
519
+ """Return true if the object is a code object.
520
+
521
+ Code objects provide these attributes:
522
+ co_argcount number of arguments (not including *, ** args
523
+ or keyword only arguments)
524
+ co_code string of raw compiled bytecode
525
+ co_cellvars tuple of names of cell variables
526
+ co_consts tuple of constants used in the bytecode
527
+ co_filename name of file in which this code object was created
528
+ co_firstlineno number of first line in Python source code
529
+ co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
530
+ | 16=nested | 32=generator | 64=nofree | 128=coroutine
531
+ | 256=iterable_coroutine | 512=async_generator
532
+ co_freevars tuple of names of free variables
533
+ co_posonlyargcount number of positional only arguments
534
+ co_kwonlyargcount number of keyword only arguments (not including ** arg)
535
+ co_lnotab encoded mapping of line numbers to bytecode indices
536
+ co_name name with which this code object was defined
537
+ co_names tuple of names other than arguments and function locals
538
+ co_nlocals number of local variables
539
+ co_stacksize virtual machine stack space required
540
+ co_varnames tuple of names of arguments and local variables"""
541
+ return isinstance(object, types.CodeType)
542
+
543
+ def isbuiltin(object):
544
+ """Return true if the object is a built-in function or method.
545
+
546
+ Built-in functions and methods provide these attributes:
547
+ __doc__ documentation string
548
+ __name__ original name of this function or method
549
+ __self__ instance to which a method is bound, or None"""
550
+ return isinstance(object, types.BuiltinFunctionType)
551
+
552
+ def ismethodwrapper(object):
553
+ """Return true if the object is a method wrapper."""
554
+ return isinstance(object, types.MethodWrapperType)
555
+
556
+ def isroutine(object):
557
+ """Return true if the object is any kind of function or method."""
558
+ return (isbuiltin(object)
559
+ or isfunction(object)
560
+ or ismethod(object)
561
+ or ismethoddescriptor(object)
562
+ or ismethodwrapper(object))
563
+
564
+ def isabstract(object):
565
+ """Return true if the object is an abstract base class (ABC)."""
566
+ if not isinstance(object, type):
567
+ return False
568
+ if object.__flags__ & TPFLAGS_IS_ABSTRACT:
569
+ return True
570
+ if not issubclass(type(object), abc.ABCMeta):
571
+ return False
572
+ if hasattr(object, '__abstractmethods__'):
573
+ # It looks like ABCMeta.__new__ has finished running;
574
+ # TPFLAGS_IS_ABSTRACT should have been accurate.
575
+ return False
576
+ # It looks like ABCMeta.__new__ has not finished running yet; we're
577
+ # probably in __init_subclass__. We'll look for abstractmethods manually.
578
+ for name, value in object.__dict__.items():
579
+ if getattr(value, "__isabstractmethod__", False):
580
+ return True
581
+ for base in object.__bases__:
582
+ for name in getattr(base, "__abstractmethods__", ()):
583
+ value = getattr(object, name, None)
584
+ if getattr(value, "__isabstractmethod__", False):
585
+ return True
586
+ return False
587
+
588
+ def _getmembers(object, predicate, getter):
589
+ results = []
590
+ processed = set()
591
+ names = dir(object)
592
+ if isclass(object):
593
+ mro = getmro(object)
594
+ # add any DynamicClassAttributes to the list of names if object is a class;
595
+ # this may result in duplicate entries if, for example, a virtual
596
+ # attribute with the same name as a DynamicClassAttribute exists
597
+ try:
598
+ for base in object.__bases__:
599
+ for k, v in base.__dict__.items():
600
+ if isinstance(v, types.DynamicClassAttribute):
601
+ names.append(k)
602
+ except AttributeError:
603
+ pass
604
+ else:
605
+ mro = ()
606
+ for key in names:
607
+ # First try to get the value via getattr. Some descriptors don't
608
+ # like calling their __get__ (see bug #1785), so fall back to
609
+ # looking in the __dict__.
610
+ try:
611
+ value = getter(object, key)
612
+ # handle the duplicate key
613
+ if key in processed:
614
+ raise AttributeError
615
+ except AttributeError:
616
+ for base in mro:
617
+ if key in base.__dict__:
618
+ value = base.__dict__[key]
619
+ break
620
+ else:
621
+ # could be a (currently) missing slot member, or a buggy
622
+ # __dir__; discard and move on
623
+ continue
624
+ if not predicate or predicate(value):
625
+ results.append((key, value))
626
+ processed.add(key)
627
+ results.sort(key=lambda pair: pair[0])
628
+ return results
629
+
630
+ def getmembers(object, predicate=None):
631
+ """Return all members of an object as (name, value) pairs sorted by name.
632
+ Optionally, only return members that satisfy a given predicate."""
633
+ return _getmembers(object, predicate, getattr)
634
+
635
+ def getmembers_static(object, predicate=None):
636
+ """Return all members of an object as (name, value) pairs sorted by name
637
+ without triggering dynamic lookup via the descriptor protocol,
638
+ __getattr__ or __getattribute__. Optionally, only return members that
639
+ satisfy a given predicate.
640
+
641
+ Note: this function may not be able to retrieve all members
642
+ that getmembers can fetch (like dynamically created attributes)
643
+ and may find members that getmembers can't (like descriptors
644
+ that raise AttributeError). It can also return descriptor objects
645
+ instead of instance members in some cases.
646
+ """
647
+ return _getmembers(object, predicate, getattr_static)
648
+
649
+ Attribute = namedtuple('Attribute', 'name kind defining_class object')
650
+
651
+ def classify_class_attrs(cls):
652
+ """Return list of attribute-descriptor tuples.
653
+
654
+ For each name in dir(cls), the return list contains a 4-tuple
655
+ with these elements:
656
+
657
+ 0. The name (a string).
658
+
659
+ 1. The kind of attribute this is, one of these strings:
660
+ 'class method' created via classmethod()
661
+ 'static method' created via staticmethod()
662
+ 'property' created via property()
663
+ 'method' any other flavor of method or descriptor
664
+ 'data' not a method
665
+
666
+ 2. The class which defined this attribute (a class).
667
+
668
+ 3. The object as obtained by calling getattr; if this fails, or if the
669
+ resulting object does not live anywhere in the class' mro (including
670
+ metaclasses) then the object is looked up in the defining class's
671
+ dict (found by walking the mro).
672
+
673
+ If one of the items in dir(cls) is stored in the metaclass it will now
674
+ be discovered and not have None be listed as the class in which it was
675
+ defined. Any items whose home class cannot be discovered are skipped.
676
+ """
677
+
678
+ mro = getmro(cls)
679
+ metamro = getmro(type(cls)) # for attributes stored in the metaclass
680
+ metamro = tuple(cls for cls in metamro if cls not in (type, object))
681
+ class_bases = (cls,) + mro
682
+ all_bases = class_bases + metamro
683
+ names = dir(cls)
684
+ # :dd any DynamicClassAttributes to the list of names;
685
+ # this may result in duplicate entries if, for example, a virtual
686
+ # attribute with the same name as a DynamicClassAttribute exists.
687
+ for base in mro:
688
+ for k, v in base.__dict__.items():
689
+ if isinstance(v, types.DynamicClassAttribute) and v.fget is not None:
690
+ names.append(k)
691
+ result = []
692
+ processed = set()
693
+
694
+ for name in names:
695
+ # Get the object associated with the name, and where it was defined.
696
+ # Normal objects will be looked up with both getattr and directly in
697
+ # its class' dict (in case getattr fails [bug #1785], and also to look
698
+ # for a docstring).
699
+ # For DynamicClassAttributes on the second pass we only look in the
700
+ # class's dict.
701
+ #
702
+ # Getting an obj from the __dict__ sometimes reveals more than
703
+ # using getattr. Static and class methods are dramatic examples.
704
+ homecls = None
705
+ get_obj = None
706
+ dict_obj = None
707
+ if name not in processed:
708
+ try:
709
+ if name == '__dict__':
710
+ raise Exception("__dict__ is special, don't want the proxy")
711
+ get_obj = getattr(cls, name)
712
+ except Exception:
713
+ pass
714
+ else:
715
+ homecls = getattr(get_obj, "__objclass__", homecls)
716
+ if homecls not in class_bases:
717
+ # if the resulting object does not live somewhere in the
718
+ # mro, drop it and search the mro manually
719
+ homecls = None
720
+ last_cls = None
721
+ # first look in the classes
722
+ for srch_cls in class_bases:
723
+ srch_obj = getattr(srch_cls, name, None)
724
+ if srch_obj is get_obj:
725
+ last_cls = srch_cls
726
+ # then check the metaclasses
727
+ for srch_cls in metamro:
728
+ try:
729
+ srch_obj = srch_cls.__getattr__(cls, name)
730
+ except AttributeError:
731
+ continue
732
+ if srch_obj is get_obj:
733
+ last_cls = srch_cls
734
+ if last_cls is not None:
735
+ homecls = last_cls
736
+ for base in all_bases:
737
+ if name in base.__dict__:
738
+ dict_obj = base.__dict__[name]
739
+ if homecls not in metamro:
740
+ homecls = base
741
+ break
742
+ if homecls is None:
743
+ # unable to locate the attribute anywhere, most likely due to
744
+ # buggy custom __dir__; discard and move on
745
+ continue
746
+ obj = get_obj if get_obj is not None else dict_obj
747
+ # Classify the object or its descriptor.
748
+ if isinstance(dict_obj, (staticmethod, types.BuiltinMethodType)):
749
+ kind = "static method"
750
+ obj = dict_obj
751
+ elif isinstance(dict_obj, (classmethod, types.ClassMethodDescriptorType)):
752
+ kind = "class method"
753
+ obj = dict_obj
754
+ elif isinstance(dict_obj, property):
755
+ kind = "property"
756
+ obj = dict_obj
757
+ elif isroutine(obj):
758
+ kind = "method"
759
+ else:
760
+ kind = "data"
761
+ result.append(Attribute(name, kind, homecls, obj))
762
+ processed.add(name)
763
+ return result
764
+
765
+ # ----------------------------------------------------------- class helpers
766
+
767
+ def getmro(cls):
768
+ "Return tuple of base classes (including cls) in method resolution order."
769
+ return cls.__mro__
770
+
771
+ # -------------------------------------------------------- function helpers
772
+
773
+ def unwrap(func, *, stop=None):
774
+ """Get the object wrapped by *func*.
775
+
776
+ Follows the chain of :attr:`__wrapped__` attributes returning the last
777
+ object in the chain.
778
+
779
+ *stop* is an optional callback accepting an object in the wrapper chain
780
+ as its sole argument that allows the unwrapping to be terminated early if
781
+ the callback returns a true value. If the callback never returns a true
782
+ value, the last object in the chain is returned as usual. For example,
783
+ :func:`signature` uses this to stop unwrapping if any object in the
784
+ chain has a ``__signature__`` attribute defined.
785
+
786
+ :exc:`ValueError` is raised if a cycle is encountered.
787
+
788
+ """
789
+ f = func # remember the original func for error reporting
790
+ # Memoise by id to tolerate non-hashable objects, but store objects to
791
+ # ensure they aren't destroyed, which would allow their IDs to be reused.
792
+ memo = {id(f): f}
793
+ recursion_limit = sys.getrecursionlimit()
794
+ while not isinstance(func, type) and hasattr(func, '__wrapped__'):
795
+ if stop is not None and stop(func):
796
+ break
797
+ func = func.__wrapped__
798
+ id_func = id(func)
799
+ if (id_func in memo) or (len(memo) >= recursion_limit):
800
+ raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
801
+ memo[id_func] = func
802
+ return func
803
+
804
+ # -------------------------------------------------- source code extraction
805
+ def indentsize(line):
806
+ """Return the indent size, in spaces, at the start of a line of text."""
807
+ expline = line.expandtabs()
808
+ return len(expline) - len(expline.lstrip())
809
+
810
+ def _findclass(func):
811
+ cls = sys.modules.get(func.__module__)
812
+ if cls is None:
813
+ return None
814
+ for name in func.__qualname__.split('.')[:-1]:
815
+ cls = getattr(cls, name)
816
+ if not isclass(cls):
817
+ return None
818
+ return cls
819
+
820
+ def _finddoc(obj):
821
+ if isclass(obj):
822
+ for base in obj.__mro__:
823
+ if base is not object:
824
+ try:
825
+ doc = base.__doc__
826
+ except AttributeError:
827
+ continue
828
+ if doc is not None:
829
+ return doc
830
+ return None
831
+
832
+ if ismethod(obj):
833
+ name = obj.__func__.__name__
834
+ self = obj.__self__
835
+ if (isclass(self) and
836
+ getattr(getattr(self, name, None), '__func__') is obj.__func__):
837
+ # classmethod
838
+ cls = self
839
+ else:
840
+ cls = self.__class__
841
+ elif isfunction(obj):
842
+ name = obj.__name__
843
+ cls = _findclass(obj)
844
+ if cls is None or getattr(cls, name) is not obj:
845
+ return None
846
+ elif isbuiltin(obj):
847
+ name = obj.__name__
848
+ self = obj.__self__
849
+ if (isclass(self) and
850
+ self.__qualname__ + '.' + name == obj.__qualname__):
851
+ # classmethod
852
+ cls = self
853
+ else:
854
+ cls = self.__class__
855
+ # Should be tested before isdatadescriptor().
856
+ elif isinstance(obj, property):
857
+ name = obj.__name__
858
+ cls = _findclass(obj.fget)
859
+ if cls is None or getattr(cls, name) is not obj:
860
+ return None
861
+ elif ismethoddescriptor(obj) or isdatadescriptor(obj):
862
+ name = obj.__name__
863
+ cls = obj.__objclass__
864
+ if getattr(cls, name) is not obj:
865
+ return None
866
+ if ismemberdescriptor(obj):
867
+ slots = getattr(cls, '__slots__', None)
868
+ if isinstance(slots, dict) and name in slots:
869
+ return slots[name]
870
+ else:
871
+ return None
872
+ for base in cls.__mro__:
873
+ try:
874
+ doc = getattr(base, name).__doc__
875
+ except AttributeError:
876
+ continue
877
+ if doc is not None:
878
+ return doc
879
+ return None
880
+
881
+ def getdoc(object):
882
+ """Get the documentation string for an object.
883
+
884
+ All tabs are expanded to spaces. To clean up docstrings that are
885
+ indented to line up with blocks of code, any whitespace than can be
886
+ uniformly removed from the second line onwards is removed."""
887
+ try:
888
+ doc = object.__doc__
889
+ except AttributeError:
890
+ return None
891
+ if doc is None:
892
+ try:
893
+ doc = _finddoc(object)
894
+ except (AttributeError, TypeError):
895
+ return None
896
+ if not isinstance(doc, str):
897
+ return None
898
+ return cleandoc(doc)
899
+
900
+ def cleandoc(doc):
901
+ """Clean up indentation from docstrings.
902
+
903
+ Any whitespace that can be uniformly removed from the second line
904
+ onwards is removed."""
905
+ lines = doc.expandtabs().split('\n')
906
+
907
+ # Find minimum indentation of any non-blank lines after first line.
908
+ margin = sys.maxsize
909
+ for line in lines[1:]:
910
+ content = len(line.lstrip(' '))
911
+ if content:
912
+ indent = len(line) - content
913
+ margin = min(margin, indent)
914
+ # Remove indentation.
915
+ if lines:
916
+ lines[0] = lines[0].lstrip(' ')
917
+ if margin < sys.maxsize:
918
+ for i in range(1, len(lines)):
919
+ lines[i] = lines[i][margin:]
920
+ # Remove any trailing or leading blank lines.
921
+ while lines and not lines[-1]:
922
+ lines.pop()
923
+ while lines and not lines[0]:
924
+ lines.pop(0)
925
+ return '\n'.join(lines)
926
+
927
+
928
+ def getfile(object):
929
+ """Work out which source or compiled file an object was defined in."""
930
+ if ismodule(object):
931
+ if getattr(object, '__file__', None):
932
+ return object.__file__
933
+ raise TypeError('{!r} is a built-in module'.format(object))
934
+ if isclass(object):
935
+ if hasattr(object, '__module__'):
936
+ module = sys.modules.get(object.__module__)
937
+ if getattr(module, '__file__', None):
938
+ return module.__file__
939
+ if object.__module__ == '__main__':
940
+ raise OSError('source code not available')
941
+ raise TypeError('{!r} is a built-in class'.format(object))
942
+ if ismethod(object):
943
+ object = object.__func__
944
+ if isfunction(object):
945
+ object = object.__code__
946
+ if istraceback(object):
947
+ object = object.tb_frame
948
+ if isframe(object):
949
+ object = object.f_code
950
+ if iscode(object):
951
+ return object.co_filename
952
+ raise TypeError('module, class, method, function, traceback, frame, or '
953
+ 'code object was expected, got {}'.format(
954
+ type(object).__name__))
955
+
956
+ def getmodulename(path):
957
+ """Return the module name for a given file, or None."""
958
+ fname = os.path.basename(path)
959
+ # Check for paths that look like an actual module file
960
+ suffixes = [(-len(suffix), suffix)
961
+ for suffix in importlib.machinery.all_suffixes()]
962
+ suffixes.sort() # try longest suffixes first, in case they overlap
963
+ for neglen, suffix in suffixes:
964
+ if fname.endswith(suffix):
965
+ return fname[:neglen]
966
+ return None
967
+
968
+ def getsourcefile(object):
969
+ """Return the filename that can be used to locate an object's source.
970
+ Return None if no way can be identified to get the source.
971
+ """
972
+ filename = getfile(object)
973
+ all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
974
+ all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
975
+ if any(filename.endswith(s) for s in all_bytecode_suffixes):
976
+ filename = (os.path.splitext(filename)[0] +
977
+ importlib.machinery.SOURCE_SUFFIXES[0])
978
+ elif any(filename.endswith(s) for s in
979
+ importlib.machinery.EXTENSION_SUFFIXES):
980
+ return None
981
+ elif filename.endswith(".fwork"):
982
+ # Apple mobile framework markers are another type of non-source file
983
+ return None
984
+
985
+ # return a filename found in the linecache even if it doesn't exist on disk
986
+ if filename in linecache.cache:
987
+ return filename
988
+ if os.path.exists(filename):
989
+ return filename
990
+ # only return a non-existent filename if the module has a PEP 302 loader
991
+ module = getmodule(object, filename)
992
+ if getattr(module, '__loader__', None) is not None:
993
+ return filename
994
+ elif getattr(getattr(module, "__spec__", None), "loader", None) is not None:
995
+ return filename
996
+
997
+ def getabsfile(object, _filename=None):
998
+ """Return an absolute path to the source or compiled file for an object.
999
+
1000
+ The idea is for each object to have a unique origin, so this routine
1001
+ normalizes the result as much as possible."""
1002
+ if _filename is None:
1003
+ _filename = getsourcefile(object) or getfile(object)
1004
+ return os.path.normcase(os.path.abspath(_filename))
1005
+
1006
+ modulesbyfile = {}
1007
+ _filesbymodname = {}
1008
+
1009
+ def getmodule(object, _filename=None):
1010
+ """Return the module an object was defined in, or None if not found."""
1011
+ if ismodule(object):
1012
+ return object
1013
+ if hasattr(object, '__module__'):
1014
+ return sys.modules.get(object.__module__)
1015
+
1016
+ # Try the filename to modulename cache
1017
+ if _filename is not None and _filename in modulesbyfile:
1018
+ return sys.modules.get(modulesbyfile[_filename])
1019
+ # Try the cache again with the absolute file name
1020
+ try:
1021
+ file = getabsfile(object, _filename)
1022
+ except (TypeError, FileNotFoundError):
1023
+ return None
1024
+ if file in modulesbyfile:
1025
+ return sys.modules.get(modulesbyfile[file])
1026
+ # Update the filename to module name cache and check yet again
1027
+ # Copy sys.modules in order to cope with changes while iterating
1028
+ for modname, module in sys.modules.copy().items():
1029
+ if ismodule(module) and hasattr(module, '__file__'):
1030
+ f = module.__file__
1031
+ if f == _filesbymodname.get(modname, None):
1032
+ # Have already mapped this module, so skip it
1033
+ continue
1034
+ _filesbymodname[modname] = f
1035
+ f = getabsfile(module)
1036
+ # Always map to the name the module knows itself by
1037
+ modulesbyfile[f] = modulesbyfile[
1038
+ os.path.realpath(f)] = module.__name__
1039
+ if file in modulesbyfile:
1040
+ return sys.modules.get(modulesbyfile[file])
1041
+ # Check the main module
1042
+ main = sys.modules['__main__']
1043
+ if not hasattr(object, '__name__'):
1044
+ return None
1045
+ if hasattr(main, object.__name__):
1046
+ mainobject = getattr(main, object.__name__)
1047
+ if mainobject is object:
1048
+ return main
1049
+ # Check builtins
1050
+ builtin = sys.modules['builtins']
1051
+ if hasattr(builtin, object.__name__):
1052
+ builtinobject = getattr(builtin, object.__name__)
1053
+ if builtinobject is object:
1054
+ return builtin
1055
+
1056
+
1057
+ class ClassFoundException(Exception):
1058
+ pass
1059
+
1060
+
1061
+ def findsource(object):
1062
+ """Return the entire source file and starting line number for an object.
1063
+
1064
+ The argument may be a module, class, method, function, traceback, frame,
1065
+ or code object. The source code is returned as a list of all the lines
1066
+ in the file and the line number indexes a line in that list. An OSError
1067
+ is raised if the source code cannot be retrieved."""
1068
+
1069
+ file = getsourcefile(object)
1070
+ if file:
1071
+ # Invalidate cache if needed.
1072
+ linecache.checkcache(file)
1073
+ else:
1074
+ file = getfile(object)
1075
+ # Allow filenames in form of "<something>" to pass through.
1076
+ # `doctest` monkeypatches `linecache` module to enable
1077
+ # inspection, so let `linecache.getlines` to be called.
1078
+ if (not (file.startswith('<') and file.endswith('>'))) or file.endswith('.fwork'):
1079
+ raise OSError('source code not available')
1080
+
1081
+ module = getmodule(object, file)
1082
+ if module:
1083
+ lines = linecache.getlines(file, module.__dict__)
1084
+ if not lines and file.startswith('<') and hasattr(object, "__code__"):
1085
+ lines = linecache._getlines_from_code(object.__code__)
1086
+ else:
1087
+ lines = linecache.getlines(file)
1088
+ if not lines:
1089
+ raise OSError('could not get source code')
1090
+
1091
+ if ismodule(object):
1092
+ return lines, 0
1093
+
1094
+ if isclass(object):
1095
+ try:
1096
+ lnum = vars(object)['__firstlineno__'] - 1
1097
+ except (TypeError, KeyError):
1098
+ raise OSError('source code not available')
1099
+ if lnum >= len(lines):
1100
+ raise OSError('lineno is out of bounds')
1101
+ return lines, lnum
1102
+
1103
+ if ismethod(object):
1104
+ object = object.__func__
1105
+ if isfunction(object):
1106
+ object = object.__code__
1107
+ if istraceback(object):
1108
+ object = object.tb_frame
1109
+ if isframe(object):
1110
+ object = object.f_code
1111
+ if iscode(object):
1112
+ if not hasattr(object, 'co_firstlineno'):
1113
+ raise OSError('could not find function definition')
1114
+ lnum = object.co_firstlineno - 1
1115
+ if lnum >= len(lines):
1116
+ raise OSError('lineno is out of bounds')
1117
+ return lines, lnum
1118
+ raise OSError('could not find code object')
1119
+
1120
+ def getcomments(object):
1121
+ """Get lines of comments immediately preceding an object's source code.
1122
+
1123
+ Returns None when source can't be found.
1124
+ """
1125
+ try:
1126
+ lines, lnum = findsource(object)
1127
+ except (OSError, TypeError):
1128
+ return None
1129
+
1130
+ if ismodule(object):
1131
+ # Look for a comment block at the top of the file.
1132
+ start = 0
1133
+ if lines and lines[0][:2] == '#!': start = 1
1134
+ while start < len(lines) and lines[start].strip() in ('', '#'):
1135
+ start = start + 1
1136
+ if start < len(lines) and lines[start][:1] == '#':
1137
+ comments = []
1138
+ end = start
1139
+ while end < len(lines) and lines[end][:1] == '#':
1140
+ comments.append(lines[end].expandtabs())
1141
+ end = end + 1
1142
+ return ''.join(comments)
1143
+
1144
+ # Look for a preceding block of comments at the same indentation.
1145
+ elif lnum > 0:
1146
+ indent = indentsize(lines[lnum])
1147
+ end = lnum - 1
1148
+ if end >= 0 and lines[end].lstrip()[:1] == '#' and \
1149
+ indentsize(lines[end]) == indent:
1150
+ comments = [lines[end].expandtabs().lstrip()]
1151
+ if end > 0:
1152
+ end = end - 1
1153
+ comment = lines[end].expandtabs().lstrip()
1154
+ while comment[:1] == '#' and indentsize(lines[end]) == indent:
1155
+ comments[:0] = [comment]
1156
+ end = end - 1
1157
+ if end < 0: break
1158
+ comment = lines[end].expandtabs().lstrip()
1159
+ while comments and comments[0].strip() == '#':
1160
+ comments[:1] = []
1161
+ while comments and comments[-1].strip() == '#':
1162
+ comments[-1:] = []
1163
+ return ''.join(comments)
1164
+
1165
+ class EndOfBlock(Exception): pass
1166
+
1167
+ class BlockFinder:
1168
+ """Provide a tokeneater() method to detect the end of a code block."""
1169
+ def __init__(self):
1170
+ self.indent = 0
1171
+ self.singleline = False
1172
+ self.started = False
1173
+ self.passline = False
1174
+ self.indecorator = False
1175
+ self.last = 1
1176
+ self.body_col0 = None
1177
+
1178
+ def tokeneater(self, type, token, srowcol, erowcol, line):
1179
+ if not self.started and not self.indecorator:
1180
+ if type in (tokenize.INDENT, tokenize.COMMENT, tokenize.NL):
1181
+ pass
1182
+ elif token == "async":
1183
+ pass
1184
+ # skip any decorators
1185
+ elif token == "@":
1186
+ self.indecorator = True
1187
+ else:
1188
+ # For "def" and "class" scan to the end of the block.
1189
+ # For "lambda" and generator expression scan to
1190
+ # the end of the logical line.
1191
+ self.singleline = token not in ("def", "class")
1192
+ self.started = True
1193
+ self.passline = True # skip to the end of the line
1194
+ elif type == tokenize.NEWLINE:
1195
+ self.passline = False # stop skipping when a NEWLINE is seen
1196
+ self.last = srowcol[0]
1197
+ if self.singleline:
1198
+ raise EndOfBlock
1199
+ # hitting a NEWLINE when in a decorator without args
1200
+ # ends the decorator
1201
+ if self.indecorator:
1202
+ self.indecorator = False
1203
+ elif self.passline:
1204
+ pass
1205
+ elif type == tokenize.INDENT:
1206
+ if self.body_col0 is None and self.started:
1207
+ self.body_col0 = erowcol[1]
1208
+ self.indent = self.indent + 1
1209
+ self.passline = True
1210
+ elif type == tokenize.DEDENT:
1211
+ self.indent = self.indent - 1
1212
+ # the end of matching indent/dedent pairs end a block
1213
+ # (note that this only works for "def"/"class" blocks,
1214
+ # not e.g. for "if: else:" or "try: finally:" blocks)
1215
+ if self.indent <= 0:
1216
+ raise EndOfBlock
1217
+ elif type == tokenize.COMMENT:
1218
+ if self.body_col0 is not None and srowcol[1] >= self.body_col0:
1219
+ # Include comments if indented at least as much as the block
1220
+ self.last = srowcol[0]
1221
+ elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
1222
+ # any other token on the same indentation level end the previous
1223
+ # block as well, except the pseudo-tokens COMMENT and NL.
1224
+ raise EndOfBlock
1225
+
1226
+ def getblock(lines):
1227
+ """Extract the block of code at the top of the given list of lines."""
1228
+ blockfinder = BlockFinder()
1229
+ try:
1230
+ tokens = tokenize.generate_tokens(iter(lines).__next__)
1231
+ for _token in tokens:
1232
+ blockfinder.tokeneater(*_token)
1233
+ except (EndOfBlock, IndentationError):
1234
+ pass
1235
+ except SyntaxError as e:
1236
+ if "unmatched" not in e.msg:
1237
+ raise e from None
1238
+ _, *_token_info = _token
1239
+ try:
1240
+ blockfinder.tokeneater(tokenize.NEWLINE, *_token_info)
1241
+ except (EndOfBlock, IndentationError):
1242
+ pass
1243
+ return lines[:blockfinder.last]
1244
+
1245
+ def getsourcelines(object):
1246
+ """Return a list of source lines and starting line number for an object.
1247
+
1248
+ The argument may be a module, class, method, function, traceback, frame,
1249
+ or code object. The source code is returned as a list of the lines
1250
+ corresponding to the object and the line number indicates where in the
1251
+ original source file the first line of code was found. An OSError is
1252
+ raised if the source code cannot be retrieved."""
1253
+ object = unwrap(object)
1254
+ lines, lnum = findsource(object)
1255
+
1256
+ if istraceback(object):
1257
+ object = object.tb_frame
1258
+
1259
+ # for module or frame that corresponds to module, return all source lines
1260
+ if (ismodule(object) or
1261
+ (isframe(object) and object.f_code.co_name == "<module>")):
1262
+ return lines, 0
1263
+ else:
1264
+ return getblock(lines[lnum:]), lnum + 1
1265
+
1266
+ def getsource(object):
1267
+ """Return the text of the source code for an object.
1268
+
1269
+ The argument may be a module, class, method, function, traceback, frame,
1270
+ or code object. The source code is returned as a single string. An
1271
+ OSError is raised if the source code cannot be retrieved."""
1272
+ lines, lnum = getsourcelines(object)
1273
+ return ''.join(lines)
1274
+
1275
+ # --------------------------------------------------- class tree extraction
1276
+ def walktree(classes, children, parent):
1277
+ """Recursive helper function for getclasstree()."""
1278
+ results = []
1279
+ classes.sort(key=attrgetter('__module__', '__name__'))
1280
+ for c in classes:
1281
+ results.append((c, c.__bases__))
1282
+ if c in children:
1283
+ results.append(walktree(children[c], children, c))
1284
+ return results
1285
+
1286
+ def getclasstree(classes, unique=False):
1287
+ """Arrange the given list of classes into a hierarchy of nested lists.
1288
+
1289
+ Where a nested list appears, it contains classes derived from the class
1290
+ whose entry immediately precedes the list. Each entry is a 2-tuple
1291
+ containing a class and a tuple of its base classes. If the 'unique'
1292
+ argument is true, exactly one entry appears in the returned structure
1293
+ for each class in the given list. Otherwise, classes using multiple
1294
+ inheritance and their descendants will appear multiple times."""
1295
+ children = {}
1296
+ roots = []
1297
+ for c in classes:
1298
+ if c.__bases__:
1299
+ for parent in c.__bases__:
1300
+ if parent not in children:
1301
+ children[parent] = []
1302
+ if c not in children[parent]:
1303
+ children[parent].append(c)
1304
+ if unique and parent in classes: break
1305
+ elif c not in roots:
1306
+ roots.append(c)
1307
+ for parent in children:
1308
+ if parent not in classes:
1309
+ roots.append(parent)
1310
+ return walktree(roots, children, None)
1311
+
1312
+ # ------------------------------------------------ argument list extraction
1313
+ Arguments = namedtuple('Arguments', 'args, varargs, varkw')
1314
+
1315
+ def getargs(co):
1316
+ """Get information about the arguments accepted by a code object.
1317
+
1318
+ Three things are returned: (args, varargs, varkw), where
1319
+ 'args' is the list of argument names. Keyword-only arguments are
1320
+ appended. 'varargs' and 'varkw' are the names of the * and **
1321
+ arguments or None."""
1322
+ if not iscode(co):
1323
+ raise TypeError('{!r} is not a code object'.format(co))
1324
+
1325
+ names = co.co_varnames
1326
+ nargs = co.co_argcount
1327
+ nkwargs = co.co_kwonlyargcount
1328
+ args = list(names[:nargs])
1329
+ kwonlyargs = list(names[nargs:nargs+nkwargs])
1330
+
1331
+ nargs += nkwargs
1332
+ varargs = None
1333
+ if co.co_flags & CO_VARARGS:
1334
+ varargs = co.co_varnames[nargs]
1335
+ nargs = nargs + 1
1336
+ varkw = None
1337
+ if co.co_flags & CO_VARKEYWORDS:
1338
+ varkw = co.co_varnames[nargs]
1339
+ return Arguments(args + kwonlyargs, varargs, varkw)
1340
+
1341
+
1342
+ FullArgSpec = namedtuple('FullArgSpec',
1343
+ 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
1344
+
1345
+ def getfullargspec(func):
1346
+ """Get the names and default values of a callable object's parameters.
1347
+
1348
+ A tuple of seven things is returned:
1349
+ (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations).
1350
+ 'args' is a list of the parameter names.
1351
+ 'varargs' and 'varkw' are the names of the * and ** parameters or None.
1352
+ 'defaults' is an n-tuple of the default values of the last n parameters.
1353
+ 'kwonlyargs' is a list of keyword-only parameter names.
1354
+ 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
1355
+ 'annotations' is a dictionary mapping parameter names to annotations.
1356
+
1357
+ Notable differences from inspect.signature():
1358
+ - the "self" parameter is always reported, even for bound methods
1359
+ - wrapper chains defined by __wrapped__ *not* unwrapped automatically
1360
+ """
1361
+ try:
1362
+ # Re: `skip_bound_arg=False`
1363
+ #
1364
+ # There is a notable difference in behaviour between getfullargspec
1365
+ # and Signature: the former always returns 'self' parameter for bound
1366
+ # methods, whereas the Signature always shows the actual calling
1367
+ # signature of the passed object.
1368
+ #
1369
+ # To simulate this behaviour, we "unbind" bound methods, to trick
1370
+ # inspect.signature to always return their first parameter ("self",
1371
+ # usually)
1372
+
1373
+ # Re: `follow_wrapper_chains=False`
1374
+ #
1375
+ # getfullargspec() historically ignored __wrapped__ attributes,
1376
+ # so we ensure that remains the case in 3.3+
1377
+
1378
+ sig = _signature_from_callable(func,
1379
+ follow_wrapper_chains=False,
1380
+ skip_bound_arg=False,
1381
+ sigcls=Signature,
1382
+ eval_str=False)
1383
+ except Exception as ex:
1384
+ # Most of the times 'signature' will raise ValueError.
1385
+ # But, it can also raise AttributeError, and, maybe something
1386
+ # else. So to be fully backwards compatible, we catch all
1387
+ # possible exceptions here, and reraise a TypeError.
1388
+ raise TypeError('unsupported callable') from ex
1389
+
1390
+ args = []
1391
+ varargs = None
1392
+ varkw = None
1393
+ posonlyargs = []
1394
+ kwonlyargs = []
1395
+ annotations = {}
1396
+ defaults = ()
1397
+ kwdefaults = {}
1398
+
1399
+ if sig.return_annotation is not sig.empty:
1400
+ annotations['return'] = sig.return_annotation
1401
+
1402
+ for param in sig.parameters.values():
1403
+ kind = param.kind
1404
+ name = param.name
1405
+
1406
+ if kind is _POSITIONAL_ONLY:
1407
+ posonlyargs.append(name)
1408
+ if param.default is not param.empty:
1409
+ defaults += (param.default,)
1410
+ elif kind is _POSITIONAL_OR_KEYWORD:
1411
+ args.append(name)
1412
+ if param.default is not param.empty:
1413
+ defaults += (param.default,)
1414
+ elif kind is _VAR_POSITIONAL:
1415
+ varargs = name
1416
+ elif kind is _KEYWORD_ONLY:
1417
+ kwonlyargs.append(name)
1418
+ if param.default is not param.empty:
1419
+ kwdefaults[name] = param.default
1420
+ elif kind is _VAR_KEYWORD:
1421
+ varkw = name
1422
+
1423
+ if param.annotation is not param.empty:
1424
+ annotations[name] = param.annotation
1425
+
1426
+ if not kwdefaults:
1427
+ # compatibility with 'func.__kwdefaults__'
1428
+ kwdefaults = None
1429
+
1430
+ if not defaults:
1431
+ # compatibility with 'func.__defaults__'
1432
+ defaults = None
1433
+
1434
+ return FullArgSpec(posonlyargs + args, varargs, varkw, defaults,
1435
+ kwonlyargs, kwdefaults, annotations)
1436
+
1437
+
1438
+ ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
1439
+
1440
+ def getargvalues(frame):
1441
+ """Get information about arguments passed into a particular frame.
1442
+
1443
+ A tuple of four things is returned: (args, varargs, varkw, locals).
1444
+ 'args' is a list of the argument names.
1445
+ 'varargs' and 'varkw' are the names of the * and ** arguments or None.
1446
+ 'locals' is the locals dictionary of the given frame."""
1447
+ args, varargs, varkw = getargs(frame.f_code)
1448
+ return ArgInfo(args, varargs, varkw, frame.f_locals)
1449
+
1450
+ def formatannotation(annotation, base_module=None):
1451
+ if getattr(annotation, '__module__', None) == 'typing':
1452
+ def repl(match):
1453
+ text = match.group()
1454
+ return text.removeprefix('typing.')
1455
+ return re.sub(r'[\w\.]+', repl, repr(annotation))
1456
+ if isinstance(annotation, types.GenericAlias):
1457
+ return str(annotation)
1458
+ if isinstance(annotation, type):
1459
+ if annotation.__module__ in ('builtins', base_module):
1460
+ return annotation.__qualname__
1461
+ return annotation.__module__+'.'+annotation.__qualname__
1462
+ return repr(annotation)
1463
+
1464
+ def formatannotationrelativeto(object):
1465
+ module = getattr(object, '__module__', None)
1466
+ def _formatannotation(annotation):
1467
+ return formatannotation(annotation, module)
1468
+ return _formatannotation
1469
+
1470
+
1471
+ def formatargvalues(args, varargs, varkw, locals,
1472
+ formatarg=str,
1473
+ formatvarargs=lambda name: '*' + name,
1474
+ formatvarkw=lambda name: '**' + name,
1475
+ formatvalue=lambda value: '=' + repr(value)):
1476
+ """Format an argument spec from the 4 values returned by getargvalues.
1477
+
1478
+ The first four arguments are (args, varargs, varkw, locals). The
1479
+ next four arguments are the corresponding optional formatting functions
1480
+ that are called to turn names and values into strings. The ninth
1481
+ argument is an optional function to format the sequence of arguments."""
1482
+ def convert(name, locals=locals,
1483
+ formatarg=formatarg, formatvalue=formatvalue):
1484
+ return formatarg(name) + formatvalue(locals[name])
1485
+ specs = []
1486
+ for i in range(len(args)):
1487
+ specs.append(convert(args[i]))
1488
+ if varargs:
1489
+ specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
1490
+ if varkw:
1491
+ specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
1492
+ return '(' + ', '.join(specs) + ')'
1493
+
1494
+ def _missing_arguments(f_name, argnames, pos, values):
1495
+ names = [repr(name) for name in argnames if name not in values]
1496
+ missing = len(names)
1497
+ if missing == 1:
1498
+ s = names[0]
1499
+ elif missing == 2:
1500
+ s = "{} and {}".format(*names)
1501
+ else:
1502
+ tail = ", {} and {}".format(*names[-2:])
1503
+ del names[-2:]
1504
+ s = ", ".join(names) + tail
1505
+ raise TypeError("%s() missing %i required %s argument%s: %s" %
1506
+ (f_name, missing,
1507
+ "positional" if pos else "keyword-only",
1508
+ "" if missing == 1 else "s", s))
1509
+
1510
+ def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
1511
+ atleast = len(args) - defcount
1512
+ kwonly_given = len([arg for arg in kwonly if arg in values])
1513
+ if varargs:
1514
+ plural = atleast != 1
1515
+ sig = "at least %d" % (atleast,)
1516
+ elif defcount:
1517
+ plural = True
1518
+ sig = "from %d to %d" % (atleast, len(args))
1519
+ else:
1520
+ plural = len(args) != 1
1521
+ sig = str(len(args))
1522
+ kwonly_sig = ""
1523
+ if kwonly_given:
1524
+ msg = " positional argument%s (and %d keyword-only argument%s)"
1525
+ kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
1526
+ "s" if kwonly_given != 1 else ""))
1527
+ raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
1528
+ (f_name, sig, "s" if plural else "", given, kwonly_sig,
1529
+ "was" if given == 1 and not kwonly_given else "were"))
1530
+
1531
+ def getcallargs(func, /, *positional, **named):
1532
+ """Get the mapping of arguments to values.
1533
+
1534
+ A dict is returned, with keys the function argument names (including the
1535
+ names of the * and ** arguments, if any), and values the respective bound
1536
+ values from 'positional' and 'named'."""
1537
+ spec = getfullargspec(func)
1538
+ args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
1539
+ f_name = func.__name__
1540
+ arg2value = {}
1541
+
1542
+
1543
+ if ismethod(func) and func.__self__ is not None:
1544
+ # implicit 'self' (or 'cls' for classmethods) argument
1545
+ positional = (func.__self__,) + positional
1546
+ num_pos = len(positional)
1547
+ num_args = len(args)
1548
+ num_defaults = len(defaults) if defaults else 0
1549
+
1550
+ n = min(num_pos, num_args)
1551
+ for i in range(n):
1552
+ arg2value[args[i]] = positional[i]
1553
+ if varargs:
1554
+ arg2value[varargs] = tuple(positional[n:])
1555
+ possible_kwargs = set(args + kwonlyargs)
1556
+ if varkw:
1557
+ arg2value[varkw] = {}
1558
+ for kw, value in named.items():
1559
+ if kw not in possible_kwargs:
1560
+ if not varkw:
1561
+ raise TypeError("%s() got an unexpected keyword argument %r" %
1562
+ (f_name, kw))
1563
+ arg2value[varkw][kw] = value
1564
+ continue
1565
+ if kw in arg2value:
1566
+ raise TypeError("%s() got multiple values for argument %r" %
1567
+ (f_name, kw))
1568
+ arg2value[kw] = value
1569
+ if num_pos > num_args and not varargs:
1570
+ _too_many(f_name, args, kwonlyargs, varargs, num_defaults,
1571
+ num_pos, arg2value)
1572
+ if num_pos < num_args:
1573
+ req = args[:num_args - num_defaults]
1574
+ for arg in req:
1575
+ if arg not in arg2value:
1576
+ _missing_arguments(f_name, req, True, arg2value)
1577
+ for i, arg in enumerate(args[num_args - num_defaults:]):
1578
+ if arg not in arg2value:
1579
+ arg2value[arg] = defaults[i]
1580
+ missing = 0
1581
+ for kwarg in kwonlyargs:
1582
+ if kwarg not in arg2value:
1583
+ if kwonlydefaults and kwarg in kwonlydefaults:
1584
+ arg2value[kwarg] = kwonlydefaults[kwarg]
1585
+ else:
1586
+ missing += 1
1587
+ if missing:
1588
+ _missing_arguments(f_name, kwonlyargs, False, arg2value)
1589
+ return arg2value
1590
+
1591
+ ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
1592
+
1593
+ def getclosurevars(func):
1594
+ """
1595
+ Get the mapping of free variables to their current values.
1596
+
1597
+ Returns a named tuple of dicts mapping the current nonlocal, global
1598
+ and builtin references as seen by the body of the function. A final
1599
+ set of unbound names that could not be resolved is also provided.
1600
+ """
1601
+
1602
+ if ismethod(func):
1603
+ func = func.__func__
1604
+
1605
+ if not isfunction(func):
1606
+ raise TypeError("{!r} is not a Python function".format(func))
1607
+
1608
+ code = func.__code__
1609
+ # Nonlocal references are named in co_freevars and resolved
1610
+ # by looking them up in __closure__ by positional index
1611
+ if func.__closure__ is None:
1612
+ nonlocal_vars = {}
1613
+ else:
1614
+ nonlocal_vars = {
1615
+ var : cell.cell_contents
1616
+ for var, cell in zip(code.co_freevars, func.__closure__)
1617
+ }
1618
+
1619
+ # Global and builtin references are named in co_names and resolved
1620
+ # by looking them up in __globals__ or __builtins__
1621
+ global_ns = func.__globals__
1622
+ builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
1623
+ if ismodule(builtin_ns):
1624
+ builtin_ns = builtin_ns.__dict__
1625
+ global_vars = {}
1626
+ builtin_vars = {}
1627
+ unbound_names = set()
1628
+ global_names = set()
1629
+ for instruction in dis.get_instructions(code):
1630
+ opname = instruction.opname
1631
+ name = instruction.argval
1632
+ if opname == "LOAD_ATTR":
1633
+ unbound_names.add(name)
1634
+ elif opname == "LOAD_GLOBAL":
1635
+ global_names.add(name)
1636
+ for name in global_names:
1637
+ try:
1638
+ global_vars[name] = global_ns[name]
1639
+ except KeyError:
1640
+ try:
1641
+ builtin_vars[name] = builtin_ns[name]
1642
+ except KeyError:
1643
+ unbound_names.add(name)
1644
+
1645
+ return ClosureVars(nonlocal_vars, global_vars,
1646
+ builtin_vars, unbound_names)
1647
+
1648
+ # -------------------------------------------------- stack frame extraction
1649
+
1650
+ _Traceback = namedtuple('_Traceback', 'filename lineno function code_context index')
1651
+
1652
+ class Traceback(_Traceback):
1653
+ def __new__(cls, filename, lineno, function, code_context, index, *, positions=None):
1654
+ instance = super().__new__(cls, filename, lineno, function, code_context, index)
1655
+ instance.positions = positions
1656
+ return instance
1657
+
1658
+ def __repr__(self):
1659
+ return ('Traceback(filename={!r}, lineno={!r}, function={!r}, '
1660
+ 'code_context={!r}, index={!r}, positions={!r})'.format(
1661
+ self.filename, self.lineno, self.function, self.code_context,
1662
+ self.index, self.positions))
1663
+
1664
+ def _get_code_position_from_tb(tb):
1665
+ code, instruction_index = tb.tb_frame.f_code, tb.tb_lasti
1666
+ return _get_code_position(code, instruction_index)
1667
+
1668
+ def _get_code_position(code, instruction_index):
1669
+ if instruction_index < 0:
1670
+ return (None, None, None, None)
1671
+ positions_gen = code.co_positions()
1672
+ # The nth entry in code.co_positions() corresponds to instruction (2*n)th since Python 3.10+
1673
+ return next(itertools.islice(positions_gen, instruction_index // 2, None))
1674
+
1675
+ def getframeinfo(frame, context=1):
1676
+ """Get information about a frame or traceback object.
1677
+
1678
+ A tuple of five things is returned: the filename, the line number of
1679
+ the current line, the function name, a list of lines of context from
1680
+ the source code, and the index of the current line within that list.
1681
+ The optional second argument specifies the number of lines of context
1682
+ to return, which are centered around the current line."""
1683
+ if istraceback(frame):
1684
+ positions = _get_code_position_from_tb(frame)
1685
+ lineno = frame.tb_lineno
1686
+ frame = frame.tb_frame
1687
+ else:
1688
+ lineno = frame.f_lineno
1689
+ positions = _get_code_position(frame.f_code, frame.f_lasti)
1690
+
1691
+ if positions[0] is None:
1692
+ frame, *positions = (frame, lineno, *positions[1:])
1693
+ else:
1694
+ frame, *positions = (frame, *positions)
1695
+
1696
+ lineno = positions[0]
1697
+
1698
+ if not isframe(frame):
1699
+ raise TypeError('{!r} is not a frame or traceback object'.format(frame))
1700
+
1701
+ filename = getsourcefile(frame) or getfile(frame)
1702
+ if context > 0:
1703
+ start = lineno - 1 - context//2
1704
+ try:
1705
+ lines, lnum = findsource(frame)
1706
+ except OSError:
1707
+ lines = index = None
1708
+ else:
1709
+ start = max(0, min(start, len(lines) - context))
1710
+ lines = lines[start:start+context]
1711
+ index = lineno - 1 - start
1712
+ else:
1713
+ lines = index = None
1714
+
1715
+ return Traceback(filename, lineno, frame.f_code.co_name, lines,
1716
+ index, positions=dis.Positions(*positions))
1717
+
1718
+ def getlineno(frame):
1719
+ """Get the line number from a frame object, allowing for optimization."""
1720
+ # FrameType.f_lineno is now a descriptor that grovels co_lnotab
1721
+ return frame.f_lineno
1722
+
1723
+ _FrameInfo = namedtuple('_FrameInfo', ('frame',) + Traceback._fields)
1724
+ class FrameInfo(_FrameInfo):
1725
+ def __new__(cls, frame, filename, lineno, function, code_context, index, *, positions=None):
1726
+ instance = super().__new__(cls, frame, filename, lineno, function, code_context, index)
1727
+ instance.positions = positions
1728
+ return instance
1729
+
1730
+ def __repr__(self):
1731
+ return ('FrameInfo(frame={!r}, filename={!r}, lineno={!r}, function={!r}, '
1732
+ 'code_context={!r}, index={!r}, positions={!r})'.format(
1733
+ self.frame, self.filename, self.lineno, self.function,
1734
+ self.code_context, self.index, self.positions))
1735
+
1736
+ def getouterframes(frame, context=1):
1737
+ """Get a list of records for a frame and all higher (calling) frames.
1738
+
1739
+ Each record contains a frame object, filename, line number, function
1740
+ name, a list of lines of context, and index within the context."""
1741
+ framelist = []
1742
+ while frame:
1743
+ traceback_info = getframeinfo(frame, context)
1744
+ frameinfo = (frame,) + traceback_info
1745
+ framelist.append(FrameInfo(*frameinfo, positions=traceback_info.positions))
1746
+ frame = frame.f_back
1747
+ return framelist
1748
+
1749
+ def getinnerframes(tb, context=1):
1750
+ """Get a list of records for a traceback's frame and all lower frames.
1751
+
1752
+ Each record contains a frame object, filename, line number, function
1753
+ name, a list of lines of context, and index within the context."""
1754
+ framelist = []
1755
+ while tb:
1756
+ traceback_info = getframeinfo(tb, context)
1757
+ frameinfo = (tb.tb_frame,) + traceback_info
1758
+ framelist.append(FrameInfo(*frameinfo, positions=traceback_info.positions))
1759
+ tb = tb.tb_next
1760
+ return framelist
1761
+
1762
+ def currentframe():
1763
+ """Return the frame of the caller or None if this is not possible."""
1764
+ return sys._getframe(1) if hasattr(sys, "_getframe") else None
1765
+
1766
+ def stack(context=1):
1767
+ """Return a list of records for the stack above the caller's frame."""
1768
+ return getouterframes(sys._getframe(1), context)
1769
+
1770
+ def trace(context=1):
1771
+ """Return a list of records for the stack below the current exception."""
1772
+ exc = sys.exception()
1773
+ tb = None if exc is None else exc.__traceback__
1774
+ return getinnerframes(tb, context)
1775
+
1776
+
1777
+ # ------------------------------------------------ static version of getattr
1778
+
1779
+ _sentinel = object()
1780
+ _static_getmro = type.__dict__['__mro__'].__get__
1781
+ _get_dunder_dict_of_class = type.__dict__["__dict__"].__get__
1782
+
1783
+
1784
+ def _check_instance(obj, attr):
1785
+ instance_dict = {}
1786
+ try:
1787
+ instance_dict = object.__getattribute__(obj, "__dict__")
1788
+ except AttributeError:
1789
+ pass
1790
+ return dict.get(instance_dict, attr, _sentinel)
1791
+
1792
+
1793
+ def _check_class(klass, attr):
1794
+ for entry in _static_getmro(klass):
1795
+ if _shadowed_dict(type(entry)) is _sentinel and attr in entry.__dict__:
1796
+ return entry.__dict__[attr]
1797
+ return _sentinel
1798
+
1799
+
1800
+ @functools.lru_cache()
1801
+ def _shadowed_dict_from_weakref_mro_tuple(*weakref_mro):
1802
+ for weakref_entry in weakref_mro:
1803
+ # Normally we'd have to check whether the result of weakref_entry()
1804
+ # is None here, in case the object the weakref is pointing to has died.
1805
+ # In this specific case, however, we know that the only caller of this
1806
+ # function is `_shadowed_dict()`, and that therefore this weakref is
1807
+ # guaranteed to point to an object that is still alive.
1808
+ entry = weakref_entry()
1809
+ dunder_dict = _get_dunder_dict_of_class(entry)
1810
+ if '__dict__' in dunder_dict:
1811
+ class_dict = dunder_dict['__dict__']
1812
+ if not (type(class_dict) is types.GetSetDescriptorType and
1813
+ class_dict.__name__ == "__dict__" and
1814
+ class_dict.__objclass__ is entry):
1815
+ return class_dict
1816
+ return _sentinel
1817
+
1818
+
1819
+ def _shadowed_dict(klass):
1820
+ # gh-118013: the inner function here is decorated with lru_cache for
1821
+ # performance reasons, *but* make sure not to pass strong references
1822
+ # to the items in the mro. Doing so can lead to unexpected memory
1823
+ # consumption in cases where classes are dynamically created and
1824
+ # destroyed, and the dynamically created classes happen to be the only
1825
+ # objects that hold strong references to other objects that take up a
1826
+ # significant amount of memory.
1827
+ return _shadowed_dict_from_weakref_mro_tuple(
1828
+ *[make_weakref(entry) for entry in _static_getmro(klass)]
1829
+ )
1830
+
1831
+
1832
+ def getattr_static(obj, attr, default=_sentinel):
1833
+ """Retrieve attributes without triggering dynamic lookup via the
1834
+ descriptor protocol, __getattr__ or __getattribute__.
1835
+
1836
+ Note: this function may not be able to retrieve all attributes
1837
+ that getattr can fetch (like dynamically created attributes)
1838
+ and may find attributes that getattr can't (like descriptors
1839
+ that raise AttributeError). It can also return descriptor objects
1840
+ instead of instance members in some cases. See the
1841
+ documentation for details.
1842
+ """
1843
+ instance_result = _sentinel
1844
+
1845
+ objtype = type(obj)
1846
+ if type not in _static_getmro(objtype):
1847
+ klass = objtype
1848
+ dict_attr = _shadowed_dict(klass)
1849
+ if (dict_attr is _sentinel or
1850
+ type(dict_attr) is types.MemberDescriptorType):
1851
+ instance_result = _check_instance(obj, attr)
1852
+ else:
1853
+ klass = obj
1854
+
1855
+ klass_result = _check_class(klass, attr)
1856
+
1857
+ if instance_result is not _sentinel and klass_result is not _sentinel:
1858
+ if _check_class(type(klass_result), "__get__") is not _sentinel and (
1859
+ _check_class(type(klass_result), "__set__") is not _sentinel
1860
+ or _check_class(type(klass_result), "__delete__") is not _sentinel
1861
+ ):
1862
+ return klass_result
1863
+
1864
+ if instance_result is not _sentinel:
1865
+ return instance_result
1866
+ if klass_result is not _sentinel:
1867
+ return klass_result
1868
+
1869
+ if obj is klass:
1870
+ # for types we check the metaclass too
1871
+ for entry in _static_getmro(type(klass)):
1872
+ if (
1873
+ _shadowed_dict(type(entry)) is _sentinel
1874
+ and attr in entry.__dict__
1875
+ ):
1876
+ return entry.__dict__[attr]
1877
+ if default is not _sentinel:
1878
+ return default
1879
+ raise AttributeError(attr)
1880
+
1881
+
1882
+ # ------------------------------------------------ generator introspection
1883
+
1884
+ GEN_CREATED = 'GEN_CREATED'
1885
+ GEN_RUNNING = 'GEN_RUNNING'
1886
+ GEN_SUSPENDED = 'GEN_SUSPENDED'
1887
+ GEN_CLOSED = 'GEN_CLOSED'
1888
+
1889
+ def getgeneratorstate(generator):
1890
+ """Get current state of a generator-iterator.
1891
+
1892
+ Possible states are:
1893
+ GEN_CREATED: Waiting to start execution.
1894
+ GEN_RUNNING: Currently being executed by the interpreter.
1895
+ GEN_SUSPENDED: Currently suspended at a yield expression.
1896
+ GEN_CLOSED: Execution has completed.
1897
+ """
1898
+ if generator.gi_running:
1899
+ return GEN_RUNNING
1900
+ if generator.gi_suspended:
1901
+ return GEN_SUSPENDED
1902
+ if generator.gi_frame is None:
1903
+ return GEN_CLOSED
1904
+ return GEN_CREATED
1905
+
1906
+
1907
+ def getgeneratorlocals(generator):
1908
+ """
1909
+ Get the mapping of generator local variables to their current values.
1910
+
1911
+ A dict is returned, with the keys the local variable names and values the
1912
+ bound values."""
1913
+
1914
+ if not isgenerator(generator):
1915
+ raise TypeError("{!r} is not a Python generator".format(generator))
1916
+
1917
+ frame = getattr(generator, "gi_frame", None)
1918
+ if frame is not None:
1919
+ return generator.gi_frame.f_locals
1920
+ else:
1921
+ return {}
1922
+
1923
+
1924
+ # ------------------------------------------------ coroutine introspection
1925
+
1926
+ CORO_CREATED = 'CORO_CREATED'
1927
+ CORO_RUNNING = 'CORO_RUNNING'
1928
+ CORO_SUSPENDED = 'CORO_SUSPENDED'
1929
+ CORO_CLOSED = 'CORO_CLOSED'
1930
+
1931
+ def getcoroutinestate(coroutine):
1932
+ """Get current state of a coroutine object.
1933
+
1934
+ Possible states are:
1935
+ CORO_CREATED: Waiting to start execution.
1936
+ CORO_RUNNING: Currently being executed by the interpreter.
1937
+ CORO_SUSPENDED: Currently suspended at an await expression.
1938
+ CORO_CLOSED: Execution has completed.
1939
+ """
1940
+ if coroutine.cr_running:
1941
+ return CORO_RUNNING
1942
+ if coroutine.cr_suspended:
1943
+ return CORO_SUSPENDED
1944
+ if coroutine.cr_frame is None:
1945
+ return CORO_CLOSED
1946
+ return CORO_CREATED
1947
+
1948
+
1949
+ def getcoroutinelocals(coroutine):
1950
+ """
1951
+ Get the mapping of coroutine local variables to their current values.
1952
+
1953
+ A dict is returned, with the keys the local variable names and values the
1954
+ bound values."""
1955
+ frame = getattr(coroutine, "cr_frame", None)
1956
+ if frame is not None:
1957
+ return frame.f_locals
1958
+ else:
1959
+ return {}
1960
+
1961
+
1962
+ # ----------------------------------- asynchronous generator introspection
1963
+
1964
+ AGEN_CREATED = 'AGEN_CREATED'
1965
+ AGEN_RUNNING = 'AGEN_RUNNING'
1966
+ AGEN_SUSPENDED = 'AGEN_SUSPENDED'
1967
+ AGEN_CLOSED = 'AGEN_CLOSED'
1968
+
1969
+
1970
+ def getasyncgenstate(agen):
1971
+ """Get current state of an asynchronous generator object.
1972
+
1973
+ Possible states are:
1974
+ AGEN_CREATED: Waiting to start execution.
1975
+ AGEN_RUNNING: Currently being executed by the interpreter.
1976
+ AGEN_SUSPENDED: Currently suspended at a yield expression.
1977
+ AGEN_CLOSED: Execution has completed.
1978
+ """
1979
+ if agen.ag_running:
1980
+ return AGEN_RUNNING
1981
+ if agen.ag_suspended:
1982
+ return AGEN_SUSPENDED
1983
+ if agen.ag_frame is None:
1984
+ return AGEN_CLOSED
1985
+ return AGEN_CREATED
1986
+
1987
+
1988
+ def getasyncgenlocals(agen):
1989
+ """
1990
+ Get the mapping of asynchronous generator local variables to their current
1991
+ values.
1992
+
1993
+ A dict is returned, with the keys the local variable names and values the
1994
+ bound values."""
1995
+
1996
+ if not isasyncgen(agen):
1997
+ raise TypeError(f"{agen!r} is not a Python async generator")
1998
+
1999
+ frame = getattr(agen, "ag_frame", None)
2000
+ if frame is not None:
2001
+ return agen.ag_frame.f_locals
2002
+ else:
2003
+ return {}
2004
+
2005
+
2006
+ ###############################################################################
2007
+ ### Function Signature Object (PEP 362)
2008
+ ###############################################################################
2009
+
2010
+
2011
+ _NonUserDefinedCallables = (types.WrapperDescriptorType,
2012
+ types.MethodWrapperType,
2013
+ types.ClassMethodDescriptorType,
2014
+ types.BuiltinFunctionType)
2015
+
2016
+
2017
+ def _signature_get_user_defined_method(cls, method_name, *, follow_wrapper_chains=True):
2018
+ """Private helper. Checks if ``cls`` has an attribute
2019
+ named ``method_name`` and returns it only if it is a
2020
+ pure python function.
2021
+ """
2022
+ if method_name == '__new__':
2023
+ meth = getattr(cls, method_name, None)
2024
+ else:
2025
+ meth = getattr_static(cls, method_name, None)
2026
+ if meth is None:
2027
+ return None
2028
+
2029
+ # NOTE: The meth may wraps a non-user-defined callable.
2030
+ # In this case, we treat the meth as non-user-defined callable too.
2031
+ # (e.g. cls.__new__ generated by @warnings.deprecated)
2032
+ unwrapped_meth = None
2033
+ if follow_wrapper_chains:
2034
+ unwrapped_meth = unwrap(meth, stop=(lambda m: hasattr(m, "__signature__")
2035
+ or _signature_is_builtin(m)))
2036
+
2037
+ if (isinstance(meth, _NonUserDefinedCallables)
2038
+ or isinstance(unwrapped_meth, _NonUserDefinedCallables)):
2039
+ # Once '__signature__' will be added to 'C'-level
2040
+ # callables, this check won't be necessary
2041
+ return None
2042
+ if method_name != '__new__':
2043
+ meth = _descriptor_get(meth, cls)
2044
+ return meth
2045
+
2046
+
2047
+ def _signature_get_partial(wrapped_sig, partial, extra_args=()):
2048
+ """Private helper to calculate how 'wrapped_sig' signature will
2049
+ look like after applying a 'functools.partial' object (or alike)
2050
+ on it.
2051
+ """
2052
+
2053
+ old_params = wrapped_sig.parameters
2054
+ new_params = OrderedDict(old_params.items())
2055
+
2056
+ partial_args = partial.args or ()
2057
+ partial_keywords = partial.keywords or {}
2058
+
2059
+ if extra_args:
2060
+ partial_args = extra_args + partial_args
2061
+
2062
+ try:
2063
+ ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords)
2064
+ except TypeError as ex:
2065
+ msg = 'partial object {!r} has incorrect arguments'.format(partial)
2066
+ raise ValueError(msg) from ex
2067
+
2068
+
2069
+ transform_to_kwonly = False
2070
+ for param_name, param in old_params.items():
2071
+ try:
2072
+ arg_value = ba.arguments[param_name]
2073
+ except KeyError:
2074
+ pass
2075
+ else:
2076
+ if param.kind is _POSITIONAL_ONLY:
2077
+ # If positional-only parameter is bound by partial,
2078
+ # it effectively disappears from the signature
2079
+ new_params.pop(param_name)
2080
+ continue
2081
+
2082
+ if param.kind is _POSITIONAL_OR_KEYWORD:
2083
+ if param_name in partial_keywords:
2084
+ # This means that this parameter, and all parameters
2085
+ # after it should be keyword-only (and var-positional
2086
+ # should be removed). Here's why. Consider the following
2087
+ # function:
2088
+ # foo(a, b, *args, c):
2089
+ # pass
2090
+ #
2091
+ # "partial(foo, a='spam')" will have the following
2092
+ # signature: "(*, a='spam', b, c)". Because attempting
2093
+ # to call that partial with "(10, 20)" arguments will
2094
+ # raise a TypeError, saying that "a" argument received
2095
+ # multiple values.
2096
+ transform_to_kwonly = True
2097
+ # Set the new default value
2098
+ new_params[param_name] = param.replace(default=arg_value)
2099
+ else:
2100
+ # was passed as a positional argument
2101
+ new_params.pop(param.name)
2102
+ continue
2103
+
2104
+ if param.kind is _KEYWORD_ONLY:
2105
+ # Set the new default value
2106
+ new_params[param_name] = param.replace(default=arg_value)
2107
+
2108
+ if transform_to_kwonly:
2109
+ assert param.kind is not _POSITIONAL_ONLY
2110
+
2111
+ if param.kind is _POSITIONAL_OR_KEYWORD:
2112
+ new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY)
2113
+ new_params[param_name] = new_param
2114
+ new_params.move_to_end(param_name)
2115
+ elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD):
2116
+ new_params.move_to_end(param_name)
2117
+ elif param.kind is _VAR_POSITIONAL:
2118
+ new_params.pop(param.name)
2119
+
2120
+ return wrapped_sig.replace(parameters=new_params.values())
2121
+
2122
+
2123
+ def _signature_bound_method(sig):
2124
+ """Private helper to transform signatures for unbound
2125
+ functions to bound methods.
2126
+ """
2127
+
2128
+ params = tuple(sig.parameters.values())
2129
+
2130
+ if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2131
+ raise ValueError('invalid method signature')
2132
+
2133
+ kind = params[0].kind
2134
+ if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
2135
+ # Drop first parameter:
2136
+ # '(p1, p2[, ...])' -> '(p2[, ...])'
2137
+ params = params[1:]
2138
+ else:
2139
+ if kind is not _VAR_POSITIONAL:
2140
+ # Unless we add a new parameter type we never
2141
+ # get here
2142
+ raise ValueError('invalid argument type')
2143
+ # It's a var-positional parameter.
2144
+ # Do nothing. '(*args[, ...])' -> '(*args[, ...])'
2145
+
2146
+ return sig.replace(parameters=params)
2147
+
2148
+
2149
+ def _signature_is_builtin(obj):
2150
+ """Private helper to test if `obj` is a callable that might
2151
+ support Argument Clinic's __text_signature__ protocol.
2152
+ """
2153
+ return (isbuiltin(obj) or
2154
+ ismethoddescriptor(obj) or
2155
+ isinstance(obj, _NonUserDefinedCallables) or
2156
+ # Can't test 'isinstance(type)' here, as it would
2157
+ # also be True for regular python classes.
2158
+ # Can't use the `in` operator here, as it would
2159
+ # invoke the custom __eq__ method.
2160
+ obj is type or obj is object)
2161
+
2162
+
2163
+ def _signature_is_functionlike(obj):
2164
+ """Private helper to test if `obj` is a duck type of FunctionType.
2165
+ A good example of such objects are functions compiled with
2166
+ Cython, which have all attributes that a pure Python function
2167
+ would have, but have their code statically compiled.
2168
+ """
2169
+
2170
+ if not callable(obj) or isclass(obj):
2171
+ # All function-like objects are obviously callables,
2172
+ # and not classes.
2173
+ return False
2174
+
2175
+ name = getattr(obj, '__name__', None)
2176
+ code = getattr(obj, '__code__', None)
2177
+ defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
2178
+ kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
2179
+ annotations = getattr(obj, '__annotations__', None)
2180
+
2181
+ return (isinstance(code, types.CodeType) and
2182
+ isinstance(name, str) and
2183
+ (defaults is None or isinstance(defaults, tuple)) and
2184
+ (kwdefaults is None or isinstance(kwdefaults, dict)) and
2185
+ (isinstance(annotations, (dict)) or annotations is None) )
2186
+
2187
+
2188
+ def _signature_strip_non_python_syntax(signature):
2189
+ """
2190
+ Private helper function. Takes a signature in Argument Clinic's
2191
+ extended signature format.
2192
+
2193
+ Returns a tuple of two things:
2194
+ * that signature re-rendered in standard Python syntax, and
2195
+ * the index of the "self" parameter (generally 0), or None if
2196
+ the function does not have a "self" parameter.
2197
+ """
2198
+
2199
+ if not signature:
2200
+ return signature, None
2201
+
2202
+ self_parameter = None
2203
+
2204
+ lines = [l.encode('ascii') for l in signature.split('\n') if l]
2205
+ generator = iter(lines).__next__
2206
+ token_stream = tokenize.tokenize(generator)
2207
+
2208
+ text = []
2209
+ add = text.append
2210
+
2211
+ current_parameter = 0
2212
+ OP = token.OP
2213
+ ERRORTOKEN = token.ERRORTOKEN
2214
+
2215
+ # token stream always starts with ENCODING token, skip it
2216
+ t = next(token_stream)
2217
+ assert t.type == tokenize.ENCODING
2218
+
2219
+ for t in token_stream:
2220
+ type, string = t.type, t.string
2221
+
2222
+ if type == OP:
2223
+ if string == ',':
2224
+ current_parameter += 1
2225
+
2226
+ if (type == OP) and (string == '$'):
2227
+ assert self_parameter is None
2228
+ self_parameter = current_parameter
2229
+ continue
2230
+
2231
+ add(string)
2232
+ if (string == ','):
2233
+ add(' ')
2234
+ clean_signature = ''.join(text).strip().replace("\n", "")
2235
+ return clean_signature, self_parameter
2236
+
2237
+
2238
+ def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
2239
+ """Private helper to parse content of '__text_signature__'
2240
+ and return a Signature based on it.
2241
+ """
2242
+ Parameter = cls._parameter_cls
2243
+
2244
+ clean_signature, self_parameter = _signature_strip_non_python_syntax(s)
2245
+
2246
+ program = "def foo" + clean_signature + ": pass"
2247
+
2248
+ try:
2249
+ module = ast.parse(program)
2250
+ except SyntaxError:
2251
+ module = None
2252
+
2253
+ if not isinstance(module, ast.Module):
2254
+ raise ValueError("{!r} builtin has invalid signature".format(obj))
2255
+
2256
+ f = module.body[0]
2257
+
2258
+ parameters = []
2259
+ empty = Parameter.empty
2260
+
2261
+ module = None
2262
+ module_dict = {}
2263
+
2264
+ module_name = getattr(obj, '__module__', None)
2265
+ if not module_name:
2266
+ objclass = getattr(obj, '__objclass__', None)
2267
+ module_name = getattr(objclass, '__module__', None)
2268
+
2269
+ if module_name:
2270
+ module = sys.modules.get(module_name, None)
2271
+ if module:
2272
+ module_dict = module.__dict__
2273
+ sys_module_dict = sys.modules.copy()
2274
+
2275
+ def parse_name(node):
2276
+ assert isinstance(node, ast.arg)
2277
+ if node.annotation is not None:
2278
+ raise ValueError("Annotations are not currently supported")
2279
+ return node.arg
2280
+
2281
+ def wrap_value(s):
2282
+ try:
2283
+ value = eval(s, module_dict)
2284
+ except NameError:
2285
+ try:
2286
+ value = eval(s, sys_module_dict)
2287
+ except NameError:
2288
+ raise ValueError
2289
+
2290
+ if isinstance(value, (str, int, float, bytes, bool, type(None))):
2291
+ return ast.Constant(value)
2292
+ raise ValueError
2293
+
2294
+ class RewriteSymbolics(ast.NodeTransformer):
2295
+ def visit_Attribute(self, node):
2296
+ a = []
2297
+ n = node
2298
+ while isinstance(n, ast.Attribute):
2299
+ a.append(n.attr)
2300
+ n = n.value
2301
+ if not isinstance(n, ast.Name):
2302
+ raise ValueError
2303
+ a.append(n.id)
2304
+ value = ".".join(reversed(a))
2305
+ return wrap_value(value)
2306
+
2307
+ def visit_Name(self, node):
2308
+ if not isinstance(node.ctx, ast.Load):
2309
+ raise ValueError()
2310
+ return wrap_value(node.id)
2311
+
2312
+ def visit_BinOp(self, node):
2313
+ # Support constant folding of a couple simple binary operations
2314
+ # commonly used to define default values in text signatures
2315
+ left = self.visit(node.left)
2316
+ right = self.visit(node.right)
2317
+ if not isinstance(left, ast.Constant) or not isinstance(right, ast.Constant):
2318
+ raise ValueError
2319
+ if isinstance(node.op, ast.Add):
2320
+ return ast.Constant(left.value + right.value)
2321
+ elif isinstance(node.op, ast.Sub):
2322
+ return ast.Constant(left.value - right.value)
2323
+ elif isinstance(node.op, ast.BitOr):
2324
+ return ast.Constant(left.value | right.value)
2325
+ raise ValueError
2326
+
2327
+ def p(name_node, default_node, default=empty):
2328
+ name = parse_name(name_node)
2329
+ if default_node and default_node is not _empty:
2330
+ try:
2331
+ default_node = RewriteSymbolics().visit(default_node)
2332
+ default = ast.literal_eval(default_node)
2333
+ except ValueError:
2334
+ raise ValueError("{!r} builtin has invalid signature".format(obj)) from None
2335
+ parameters.append(Parameter(name, kind, default=default, annotation=empty))
2336
+
2337
+ # non-keyword-only parameters
2338
+ total_non_kw_args = len(f.args.posonlyargs) + len(f.args.args)
2339
+ required_non_kw_args = total_non_kw_args - len(f.args.defaults)
2340
+ defaults = itertools.chain(itertools.repeat(None, required_non_kw_args), f.args.defaults)
2341
+
2342
+ kind = Parameter.POSITIONAL_ONLY
2343
+ for (name, default) in zip(f.args.posonlyargs, defaults):
2344
+ p(name, default)
2345
+
2346
+ kind = Parameter.POSITIONAL_OR_KEYWORD
2347
+ for (name, default) in zip(f.args.args, defaults):
2348
+ p(name, default)
2349
+
2350
+ # *args
2351
+ if f.args.vararg:
2352
+ kind = Parameter.VAR_POSITIONAL
2353
+ p(f.args.vararg, empty)
2354
+
2355
+ # keyword-only arguments
2356
+ kind = Parameter.KEYWORD_ONLY
2357
+ for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
2358
+ p(name, default)
2359
+
2360
+ # **kwargs
2361
+ if f.args.kwarg:
2362
+ kind = Parameter.VAR_KEYWORD
2363
+ p(f.args.kwarg, empty)
2364
+
2365
+ if self_parameter is not None:
2366
+ # Possibly strip the bound argument:
2367
+ # - We *always* strip first bound argument if
2368
+ # it is a module.
2369
+ # - We don't strip first bound argument if
2370
+ # skip_bound_arg is False.
2371
+ assert parameters
2372
+ _self = getattr(obj, '__self__', None)
2373
+ self_isbound = _self is not None
2374
+ self_ismodule = ismodule(_self)
2375
+ if self_isbound and (self_ismodule or skip_bound_arg):
2376
+ parameters.pop(0)
2377
+ else:
2378
+ # for builtins, self parameter is always positional-only!
2379
+ p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)
2380
+ parameters[0] = p
2381
+
2382
+ return cls(parameters, return_annotation=cls.empty)
2383
+
2384
+
2385
+ def _signature_from_builtin(cls, func, skip_bound_arg=True):
2386
+ """Private helper function to get signature for
2387
+ builtin callables.
2388
+ """
2389
+
2390
+ if not _signature_is_builtin(func):
2391
+ raise TypeError("{!r} is not a Python builtin "
2392
+ "function".format(func))
2393
+
2394
+ s = getattr(func, "__text_signature__", None)
2395
+ if not s:
2396
+ raise ValueError("no signature found for builtin {!r}".format(func))
2397
+
2398
+ return _signature_fromstr(cls, func, s, skip_bound_arg)
2399
+
2400
+
2401
+ def _signature_from_function(cls, func, skip_bound_arg=True,
2402
+ globals=None, locals=None, eval_str=False):
2403
+ """Private helper: constructs Signature for the given python function."""
2404
+
2405
+ is_duck_function = False
2406
+ if not isfunction(func):
2407
+ if _signature_is_functionlike(func):
2408
+ is_duck_function = True
2409
+ else:
2410
+ # If it's not a pure Python function, and not a duck type
2411
+ # of pure function:
2412
+ raise TypeError('{!r} is not a Python function'.format(func))
2413
+
2414
+ s = getattr(func, "__text_signature__", None)
2415
+ if s:
2416
+ return _signature_fromstr(cls, func, s, skip_bound_arg)
2417
+
2418
+ Parameter = cls._parameter_cls
2419
+
2420
+ # Parameter information.
2421
+ func_code = func.__code__
2422
+ pos_count = func_code.co_argcount
2423
+ arg_names = func_code.co_varnames
2424
+ posonly_count = func_code.co_posonlyargcount
2425
+ positional = arg_names[:pos_count]
2426
+ keyword_only_count = func_code.co_kwonlyargcount
2427
+ keyword_only = arg_names[pos_count:pos_count + keyword_only_count]
2428
+ annotations = get_annotations(func, globals=globals, locals=locals, eval_str=eval_str)
2429
+ defaults = func.__defaults__
2430
+ kwdefaults = func.__kwdefaults__
2431
+
2432
+ if defaults:
2433
+ pos_default_count = len(defaults)
2434
+ else:
2435
+ pos_default_count = 0
2436
+
2437
+ parameters = []
2438
+
2439
+ non_default_count = pos_count - pos_default_count
2440
+ posonly_left = posonly_count
2441
+
2442
+ # Non-keyword-only parameters w/o defaults.
2443
+ for name in positional[:non_default_count]:
2444
+ kind = _POSITIONAL_ONLY if posonly_left else _POSITIONAL_OR_KEYWORD
2445
+ annotation = annotations.get(name, _empty)
2446
+ parameters.append(Parameter(name, annotation=annotation,
2447
+ kind=kind))
2448
+ if posonly_left:
2449
+ posonly_left -= 1
2450
+
2451
+ # ... w/ defaults.
2452
+ for offset, name in enumerate(positional[non_default_count:]):
2453
+ kind = _POSITIONAL_ONLY if posonly_left else _POSITIONAL_OR_KEYWORD
2454
+ annotation = annotations.get(name, _empty)
2455
+ parameters.append(Parameter(name, annotation=annotation,
2456
+ kind=kind,
2457
+ default=defaults[offset]))
2458
+ if posonly_left:
2459
+ posonly_left -= 1
2460
+
2461
+ # *args
2462
+ if func_code.co_flags & CO_VARARGS:
2463
+ name = arg_names[pos_count + keyword_only_count]
2464
+ annotation = annotations.get(name, _empty)
2465
+ parameters.append(Parameter(name, annotation=annotation,
2466
+ kind=_VAR_POSITIONAL))
2467
+
2468
+ # Keyword-only parameters.
2469
+ for name in keyword_only:
2470
+ default = _empty
2471
+ if kwdefaults is not None:
2472
+ default = kwdefaults.get(name, _empty)
2473
+
2474
+ annotation = annotations.get(name, _empty)
2475
+ parameters.append(Parameter(name, annotation=annotation,
2476
+ kind=_KEYWORD_ONLY,
2477
+ default=default))
2478
+ # **kwargs
2479
+ if func_code.co_flags & CO_VARKEYWORDS:
2480
+ index = pos_count + keyword_only_count
2481
+ if func_code.co_flags & CO_VARARGS:
2482
+ index += 1
2483
+
2484
+ name = arg_names[index]
2485
+ annotation = annotations.get(name, _empty)
2486
+ parameters.append(Parameter(name, annotation=annotation,
2487
+ kind=_VAR_KEYWORD))
2488
+
2489
+ # Is 'func' is a pure Python function - don't validate the
2490
+ # parameters list (for correct order and defaults), it should be OK.
2491
+ return cls(parameters,
2492
+ return_annotation=annotations.get('return', _empty),
2493
+ __validate_parameters__=is_duck_function)
2494
+
2495
+
2496
+ def _descriptor_get(descriptor, obj):
2497
+ if isclass(descriptor):
2498
+ return descriptor
2499
+ get = getattr(type(descriptor), '__get__', _sentinel)
2500
+ if get is _sentinel:
2501
+ return descriptor
2502
+ return get(descriptor, obj, type(obj))
2503
+
2504
+
2505
+ def _signature_from_callable(obj, *,
2506
+ follow_wrapper_chains=True,
2507
+ skip_bound_arg=True,
2508
+ globals=None,
2509
+ locals=None,
2510
+ eval_str=False,
2511
+ sigcls):
2512
+
2513
+ """Private helper function to get signature for arbitrary
2514
+ callable objects.
2515
+ """
2516
+
2517
+ _get_signature_of = functools.partial(_signature_from_callable,
2518
+ follow_wrapper_chains=follow_wrapper_chains,
2519
+ skip_bound_arg=skip_bound_arg,
2520
+ globals=globals,
2521
+ locals=locals,
2522
+ sigcls=sigcls,
2523
+ eval_str=eval_str)
2524
+
2525
+ if not callable(obj):
2526
+ raise TypeError('{!r} is not a callable object'.format(obj))
2527
+
2528
+ if isinstance(obj, types.MethodType):
2529
+ # In this case we skip the first parameter of the underlying
2530
+ # function (usually `self` or `cls`).
2531
+ sig = _get_signature_of(obj.__func__)
2532
+
2533
+ if skip_bound_arg:
2534
+ return _signature_bound_method(sig)
2535
+ else:
2536
+ return sig
2537
+
2538
+ # Was this function wrapped by a decorator?
2539
+ if follow_wrapper_chains:
2540
+ # Unwrap until we find an explicit signature or a MethodType (which will be
2541
+ # handled explicitly below).
2542
+ obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")
2543
+ or isinstance(f, types.MethodType)))
2544
+ if isinstance(obj, types.MethodType):
2545
+ # If the unwrapped object is a *method*, we might want to
2546
+ # skip its first parameter (self).
2547
+ # See test_signature_wrapped_bound_method for details.
2548
+ return _get_signature_of(obj)
2549
+
2550
+ try:
2551
+ sig = obj.__signature__
2552
+ except AttributeError:
2553
+ pass
2554
+ else:
2555
+ if sig is not None:
2556
+ # since __text_signature__ is not writable on classes, __signature__
2557
+ # may contain text (or be a callable that returns text);
2558
+ # if so, convert it
2559
+ o_sig = sig
2560
+ if not isinstance(sig, (Signature, str)) and callable(sig):
2561
+ sig = sig()
2562
+ if isinstance(sig, str):
2563
+ sig = _signature_fromstr(sigcls, obj, sig)
2564
+ if not isinstance(sig, Signature):
2565
+ raise TypeError(
2566
+ 'unexpected object {!r} in __signature__ '
2567
+ 'attribute'.format(o_sig))
2568
+ return sig
2569
+
2570
+ try:
2571
+ partialmethod = obj.__partialmethod__
2572
+ except AttributeError:
2573
+ pass
2574
+ else:
2575
+ if isinstance(partialmethod, functools.partialmethod):
2576
+ # Unbound partialmethod (see functools.partialmethod)
2577
+ # This means, that we need to calculate the signature
2578
+ # as if it's a regular partial object, but taking into
2579
+ # account that the first positional argument
2580
+ # (usually `self`, or `cls`) will not be passed
2581
+ # automatically (as for boundmethods)
2582
+
2583
+ wrapped_sig = _get_signature_of(partialmethod.func)
2584
+
2585
+ sig = _signature_get_partial(wrapped_sig, partialmethod, (None,))
2586
+ first_wrapped_param = tuple(wrapped_sig.parameters.values())[0]
2587
+ if first_wrapped_param.kind is Parameter.VAR_POSITIONAL:
2588
+ # First argument of the wrapped callable is `*args`, as in
2589
+ # `partialmethod(lambda *args)`.
2590
+ return sig
2591
+ else:
2592
+ sig_params = tuple(sig.parameters.values())
2593
+ assert (not sig_params or
2594
+ first_wrapped_param is not sig_params[0])
2595
+ new_params = (first_wrapped_param,) + sig_params
2596
+ return sig.replace(parameters=new_params)
2597
+
2598
+ if isinstance(obj, functools.partial):
2599
+ wrapped_sig = _get_signature_of(obj.func)
2600
+ return _signature_get_partial(wrapped_sig, obj)
2601
+
2602
+ if isfunction(obj) or _signature_is_functionlike(obj):
2603
+ # If it's a pure Python function, or an object that is duck type
2604
+ # of a Python function (Cython functions, for instance), then:
2605
+ return _signature_from_function(sigcls, obj,
2606
+ skip_bound_arg=skip_bound_arg,
2607
+ globals=globals, locals=locals, eval_str=eval_str)
2608
+
2609
+ if _signature_is_builtin(obj):
2610
+ return _signature_from_builtin(sigcls, obj,
2611
+ skip_bound_arg=skip_bound_arg)
2612
+
2613
+ if isinstance(obj, type):
2614
+ # obj is a class or a metaclass
2615
+
2616
+ # First, let's see if it has an overloaded __call__ defined
2617
+ # in its metaclass
2618
+ call = _signature_get_user_defined_method(
2619
+ type(obj),
2620
+ '__call__',
2621
+ follow_wrapper_chains=follow_wrapper_chains,
2622
+ )
2623
+ if call is not None:
2624
+ return _get_signature_of(call)
2625
+
2626
+ # NOTE: The user-defined method can be a function with a thin wrapper
2627
+ # around object.__new__ (e.g., generated by `@warnings.deprecated`)
2628
+ new = _signature_get_user_defined_method(
2629
+ obj,
2630
+ '__new__',
2631
+ follow_wrapper_chains=follow_wrapper_chains,
2632
+ )
2633
+ init = _signature_get_user_defined_method(
2634
+ obj,
2635
+ '__init__',
2636
+ follow_wrapper_chains=follow_wrapper_chains,
2637
+ )
2638
+
2639
+ # Go through the MRO and see if any class has user-defined
2640
+ # pure Python __new__ or __init__ method
2641
+ for base in obj.__mro__:
2642
+ # Now we check if the 'obj' class has an own '__new__' method
2643
+ if new is not None and '__new__' in base.__dict__:
2644
+ sig = _get_signature_of(new)
2645
+ if skip_bound_arg:
2646
+ sig = _signature_bound_method(sig)
2647
+ return sig
2648
+ # or an own '__init__' method
2649
+ elif init is not None and '__init__' in base.__dict__:
2650
+ return _get_signature_of(init)
2651
+
2652
+ # At this point we know, that `obj` is a class, with no user-
2653
+ # defined '__init__', '__new__', or class-level '__call__'
2654
+
2655
+ for base in obj.__mro__[:-1]:
2656
+ # Since '__text_signature__' is implemented as a
2657
+ # descriptor that extracts text signature from the
2658
+ # class docstring, if 'obj' is derived from a builtin
2659
+ # class, its own '__text_signature__' may be 'None'.
2660
+ # Therefore, we go through the MRO (except the last
2661
+ # class in there, which is 'object') to find the first
2662
+ # class with non-empty text signature.
2663
+ try:
2664
+ text_sig = base.__text_signature__
2665
+ except AttributeError:
2666
+ pass
2667
+ else:
2668
+ if text_sig:
2669
+ # If 'base' class has a __text_signature__ attribute:
2670
+ # return a signature based on it
2671
+ return _signature_fromstr(sigcls, base, text_sig)
2672
+
2673
+ # No '__text_signature__' was found for the 'obj' class.
2674
+ # Last option is to check if its '__init__' is
2675
+ # object.__init__ or type.__init__.
2676
+ if type not in obj.__mro__:
2677
+ obj_init = obj.__init__
2678
+ obj_new = obj.__new__
2679
+ if follow_wrapper_chains:
2680
+ obj_init = unwrap(obj_init)
2681
+ obj_new = unwrap(obj_new)
2682
+ # We have a class (not metaclass), but no user-defined
2683
+ # __init__ or __new__ for it
2684
+ if obj_init is object.__init__ and obj_new is object.__new__:
2685
+ # Return a signature of 'object' builtin.
2686
+ return sigcls.from_callable(object)
2687
+ else:
2688
+ raise ValueError(
2689
+ 'no signature found for builtin type {!r}'.format(obj))
2690
+
2691
+ else:
2692
+ # An object with __call__
2693
+ call = getattr_static(type(obj), '__call__', None)
2694
+ if call is not None:
2695
+ try:
2696
+ text_sig = obj.__text_signature__
2697
+ except AttributeError:
2698
+ pass
2699
+ else:
2700
+ if text_sig:
2701
+ return _signature_fromstr(sigcls, obj, text_sig)
2702
+ call = _descriptor_get(call, obj)
2703
+ return _get_signature_of(call)
2704
+
2705
+ raise ValueError('callable {!r} is not supported by signature'.format(obj))
2706
+
2707
+
2708
+ class _void:
2709
+ """A private marker - used in Parameter & Signature."""
2710
+
2711
+
2712
+ class _empty:
2713
+ """Marker object for Signature.empty and Parameter.empty."""
2714
+
2715
+
2716
+ class _ParameterKind(enum.IntEnum):
2717
+ POSITIONAL_ONLY = 'positional-only'
2718
+ POSITIONAL_OR_KEYWORD = 'positional or keyword'
2719
+ VAR_POSITIONAL = 'variadic positional'
2720
+ KEYWORD_ONLY = 'keyword-only'
2721
+ VAR_KEYWORD = 'variadic keyword'
2722
+
2723
+ def __new__(cls, description):
2724
+ value = len(cls.__members__)
2725
+ member = int.__new__(cls, value)
2726
+ member._value_ = value
2727
+ member.description = description
2728
+ return member
2729
+
2730
+ def __str__(self):
2731
+ return self.name
2732
+
2733
+ _POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY
2734
+ _POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD
2735
+ _VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL
2736
+ _KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
2737
+ _VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
2738
+
2739
+
2740
+ class Parameter:
2741
+ """Represents a parameter in a function signature.
2742
+
2743
+ Has the following public attributes:
2744
+
2745
+ * name : str
2746
+ The name of the parameter as a string.
2747
+ * default : object
2748
+ The default value for the parameter if specified. If the
2749
+ parameter has no default value, this attribute is set to
2750
+ `Parameter.empty`.
2751
+ * annotation
2752
+ The annotation for the parameter if specified. If the
2753
+ parameter has no annotation, this attribute is set to
2754
+ `Parameter.empty`.
2755
+ * kind
2756
+ Describes how argument values are bound to the parameter.
2757
+ Possible values: `Parameter.POSITIONAL_ONLY`,
2758
+ `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
2759
+ `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
2760
+ Every value has a `description` attribute describing meaning.
2761
+ """
2762
+
2763
+ __slots__ = ('_name', '_kind', '_default', '_annotation')
2764
+
2765
+ POSITIONAL_ONLY = _POSITIONAL_ONLY
2766
+ POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
2767
+ VAR_POSITIONAL = _VAR_POSITIONAL
2768
+ KEYWORD_ONLY = _KEYWORD_ONLY
2769
+ VAR_KEYWORD = _VAR_KEYWORD
2770
+
2771
+ empty = _empty
2772
+
2773
+ def __init__(self, name, kind, *, default=_empty, annotation=_empty):
2774
+ try:
2775
+ self._kind = _ParameterKind(kind)
2776
+ except ValueError:
2777
+ raise ValueError(f'value {kind!r} is not a valid Parameter.kind')
2778
+ if default is not _empty:
2779
+ if self._kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
2780
+ msg = '{} parameters cannot have default values'
2781
+ msg = msg.format(self._kind.description)
2782
+ raise ValueError(msg)
2783
+ self._default = default
2784
+ self._annotation = annotation
2785
+
2786
+ if name is _empty:
2787
+ raise ValueError('name is a required attribute for Parameter')
2788
+
2789
+ if not isinstance(name, str):
2790
+ msg = 'name must be a str, not a {}'.format(type(name).__name__)
2791
+ raise TypeError(msg)
2792
+
2793
+ if name[0] == '.' and name[1:].isdigit():
2794
+ # These are implicit arguments generated by comprehensions. In
2795
+ # order to provide a friendlier interface to users, we recast
2796
+ # their name as "implicitN" and treat them as positional-only.
2797
+ # See issue 19611.
2798
+ if self._kind != _POSITIONAL_OR_KEYWORD:
2799
+ msg = (
2800
+ 'implicit arguments must be passed as '
2801
+ 'positional or keyword arguments, not {}'
2802
+ )
2803
+ msg = msg.format(self._kind.description)
2804
+ raise ValueError(msg)
2805
+ self._kind = _POSITIONAL_ONLY
2806
+ name = 'implicit{}'.format(name[1:])
2807
+
2808
+ # It's possible for C functions to have a positional-only parameter
2809
+ # where the name is a keyword, so for compatibility we'll allow it.
2810
+ is_keyword = iskeyword(name) and self._kind is not _POSITIONAL_ONLY
2811
+ if is_keyword or not name.isidentifier():
2812
+ raise ValueError('{!r} is not a valid parameter name'.format(name))
2813
+
2814
+ self._name = name
2815
+
2816
+ def __reduce__(self):
2817
+ return (type(self),
2818
+ (self._name, self._kind),
2819
+ {'_default': self._default,
2820
+ '_annotation': self._annotation})
2821
+
2822
+ def __setstate__(self, state):
2823
+ self._default = state['_default']
2824
+ self._annotation = state['_annotation']
2825
+
2826
+ @property
2827
+ def name(self):
2828
+ return self._name
2829
+
2830
+ @property
2831
+ def default(self):
2832
+ return self._default
2833
+
2834
+ @property
2835
+ def annotation(self):
2836
+ return self._annotation
2837
+
2838
+ @property
2839
+ def kind(self):
2840
+ return self._kind
2841
+
2842
+ def replace(self, *, name=_void, kind=_void,
2843
+ annotation=_void, default=_void):
2844
+ """Creates a customized copy of the Parameter."""
2845
+
2846
+ if name is _void:
2847
+ name = self._name
2848
+
2849
+ if kind is _void:
2850
+ kind = self._kind
2851
+
2852
+ if annotation is _void:
2853
+ annotation = self._annotation
2854
+
2855
+ if default is _void:
2856
+ default = self._default
2857
+
2858
+ return type(self)(name, kind, default=default, annotation=annotation)
2859
+
2860
+ def __str__(self):
2861
+ kind = self.kind
2862
+ formatted = self._name
2863
+
2864
+ # Add annotation and default value
2865
+ if self._annotation is not _empty:
2866
+ formatted = '{}: {}'.format(formatted,
2867
+ formatannotation(self._annotation))
2868
+
2869
+ if self._default is not _empty:
2870
+ if self._annotation is not _empty:
2871
+ formatted = '{} = {}'.format(formatted, repr(self._default))
2872
+ else:
2873
+ formatted = '{}={}'.format(formatted, repr(self._default))
2874
+
2875
+ if kind == _VAR_POSITIONAL:
2876
+ formatted = '*' + formatted
2877
+ elif kind == _VAR_KEYWORD:
2878
+ formatted = '**' + formatted
2879
+
2880
+ return formatted
2881
+
2882
+ __replace__ = replace
2883
+
2884
+ def __repr__(self):
2885
+ return '<{} "{}">'.format(self.__class__.__name__, self)
2886
+
2887
+ def __hash__(self):
2888
+ return hash((self._name, self._kind, self._annotation, self._default))
2889
+
2890
+ def __eq__(self, other):
2891
+ if self is other:
2892
+ return True
2893
+ if not isinstance(other, Parameter):
2894
+ return NotImplemented
2895
+ return (self._name == other._name and
2896
+ self._kind == other._kind and
2897
+ self._default == other._default and
2898
+ self._annotation == other._annotation)
2899
+
2900
+
2901
+ class BoundArguments:
2902
+ """Result of `Signature.bind` call. Holds the mapping of arguments
2903
+ to the function's parameters.
2904
+
2905
+ Has the following public attributes:
2906
+
2907
+ * arguments : dict
2908
+ An ordered mutable mapping of parameters' names to arguments' values.
2909
+ Does not contain arguments' default values.
2910
+ * signature : Signature
2911
+ The Signature object that created this instance.
2912
+ * args : tuple
2913
+ Tuple of positional arguments values.
2914
+ * kwargs : dict
2915
+ Dict of keyword arguments values.
2916
+ """
2917
+
2918
+ __slots__ = ('arguments', '_signature', '__weakref__')
2919
+
2920
+ def __init__(self, signature, arguments):
2921
+ self.arguments = arguments
2922
+ self._signature = signature
2923
+
2924
+ @property
2925
+ def signature(self):
2926
+ return self._signature
2927
+
2928
+ @property
2929
+ def args(self):
2930
+ args = []
2931
+ for param_name, param in self._signature.parameters.items():
2932
+ if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2933
+ break
2934
+
2935
+ try:
2936
+ arg = self.arguments[param_name]
2937
+ except KeyError:
2938
+ # We're done here. Other arguments
2939
+ # will be mapped in 'BoundArguments.kwargs'
2940
+ break
2941
+ else:
2942
+ if param.kind == _VAR_POSITIONAL:
2943
+ # *args
2944
+ args.extend(arg)
2945
+ else:
2946
+ # plain argument
2947
+ args.append(arg)
2948
+
2949
+ return tuple(args)
2950
+
2951
+ @property
2952
+ def kwargs(self):
2953
+ kwargs = {}
2954
+ kwargs_started = False
2955
+ for param_name, param in self._signature.parameters.items():
2956
+ if not kwargs_started:
2957
+ if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
2958
+ kwargs_started = True
2959
+ else:
2960
+ if param_name not in self.arguments:
2961
+ kwargs_started = True
2962
+ continue
2963
+
2964
+ if not kwargs_started:
2965
+ continue
2966
+
2967
+ try:
2968
+ arg = self.arguments[param_name]
2969
+ except KeyError:
2970
+ pass
2971
+ else:
2972
+ if param.kind == _VAR_KEYWORD:
2973
+ # **kwargs
2974
+ kwargs.update(arg)
2975
+ else:
2976
+ # plain keyword argument
2977
+ kwargs[param_name] = arg
2978
+
2979
+ return kwargs
2980
+
2981
+ def apply_defaults(self):
2982
+ """Set default values for missing arguments.
2983
+
2984
+ For variable-positional arguments (*args) the default is an
2985
+ empty tuple.
2986
+
2987
+ For variable-keyword arguments (**kwargs) the default is an
2988
+ empty dict.
2989
+ """
2990
+ arguments = self.arguments
2991
+ new_arguments = []
2992
+ for name, param in self._signature.parameters.items():
2993
+ try:
2994
+ new_arguments.append((name, arguments[name]))
2995
+ except KeyError:
2996
+ if param.default is not _empty:
2997
+ val = param.default
2998
+ elif param.kind is _VAR_POSITIONAL:
2999
+ val = ()
3000
+ elif param.kind is _VAR_KEYWORD:
3001
+ val = {}
3002
+ else:
3003
+ # This BoundArguments was likely produced by
3004
+ # Signature.bind_partial().
3005
+ continue
3006
+ new_arguments.append((name, val))
3007
+ self.arguments = dict(new_arguments)
3008
+
3009
+ def __eq__(self, other):
3010
+ if self is other:
3011
+ return True
3012
+ if not isinstance(other, BoundArguments):
3013
+ return NotImplemented
3014
+ return (self.signature == other.signature and
3015
+ self.arguments == other.arguments)
3016
+
3017
+ def __setstate__(self, state):
3018
+ self._signature = state['_signature']
3019
+ self.arguments = state['arguments']
3020
+
3021
+ def __getstate__(self):
3022
+ return {'_signature': self._signature, 'arguments': self.arguments}
3023
+
3024
+ def __repr__(self):
3025
+ args = []
3026
+ for arg, value in self.arguments.items():
3027
+ args.append('{}={!r}'.format(arg, value))
3028
+ return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args))
3029
+
3030
+
3031
+ class Signature:
3032
+ """A Signature object represents the overall signature of a function.
3033
+ It stores a Parameter object for each parameter accepted by the
3034
+ function, as well as information specific to the function itself.
3035
+
3036
+ A Signature object has the following public attributes and methods:
3037
+
3038
+ * parameters : OrderedDict
3039
+ An ordered mapping of parameters' names to the corresponding
3040
+ Parameter objects (keyword-only arguments are in the same order
3041
+ as listed in `code.co_varnames`).
3042
+ * return_annotation : object
3043
+ The annotation for the return type of the function if specified.
3044
+ If the function has no annotation for its return type, this
3045
+ attribute is set to `Signature.empty`.
3046
+ * bind(*args, **kwargs) -> BoundArguments
3047
+ Creates a mapping from positional and keyword arguments to
3048
+ parameters.
3049
+ * bind_partial(*args, **kwargs) -> BoundArguments
3050
+ Creates a partial mapping from positional and keyword arguments
3051
+ to parameters (simulating 'functools.partial' behavior.)
3052
+ """
3053
+
3054
+ __slots__ = ('_return_annotation', '_parameters')
3055
+
3056
+ _parameter_cls = Parameter
3057
+ _bound_arguments_cls = BoundArguments
3058
+
3059
+ empty = _empty
3060
+
3061
+ def __init__(self, parameters=None, *, return_annotation=_empty,
3062
+ __validate_parameters__=True):
3063
+ """Constructs Signature from the given list of Parameter
3064
+ objects and 'return_annotation'. All arguments are optional.
3065
+ """
3066
+
3067
+ if parameters is None:
3068
+ params = OrderedDict()
3069
+ else:
3070
+ if __validate_parameters__:
3071
+ params = OrderedDict()
3072
+ top_kind = _POSITIONAL_ONLY
3073
+ seen_default = False
3074
+
3075
+ for param in parameters:
3076
+ kind = param.kind
3077
+ name = param.name
3078
+
3079
+ if kind < top_kind:
3080
+ msg = (
3081
+ 'wrong parameter order: {} parameter before {} '
3082
+ 'parameter'
3083
+ )
3084
+ msg = msg.format(top_kind.description,
3085
+ kind.description)
3086
+ raise ValueError(msg)
3087
+ elif kind > top_kind:
3088
+ top_kind = kind
3089
+
3090
+ if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
3091
+ if param.default is _empty:
3092
+ if seen_default:
3093
+ # No default for this parameter, but the
3094
+ # previous parameter of had a default
3095
+ msg = 'non-default argument follows default ' \
3096
+ 'argument'
3097
+ raise ValueError(msg)
3098
+ else:
3099
+ # There is a default for this parameter.
3100
+ seen_default = True
3101
+
3102
+ if name in params:
3103
+ msg = 'duplicate parameter name: {!r}'.format(name)
3104
+ raise ValueError(msg)
3105
+
3106
+ params[name] = param
3107
+ else:
3108
+ params = OrderedDict((param.name, param) for param in parameters)
3109
+
3110
+ self._parameters = types.MappingProxyType(params)
3111
+ self._return_annotation = return_annotation
3112
+
3113
+ @classmethod
3114
+ def from_callable(cls, obj, *,
3115
+ follow_wrapped=True, globals=None, locals=None, eval_str=False):
3116
+ """Constructs Signature for the given callable object."""
3117
+ return _signature_from_callable(obj, sigcls=cls,
3118
+ follow_wrapper_chains=follow_wrapped,
3119
+ globals=globals, locals=locals, eval_str=eval_str)
3120
+
3121
+ @property
3122
+ def parameters(self):
3123
+ return self._parameters
3124
+
3125
+ @property
3126
+ def return_annotation(self):
3127
+ return self._return_annotation
3128
+
3129
+ def replace(self, *, parameters=_void, return_annotation=_void):
3130
+ """Creates a customized copy of the Signature.
3131
+ Pass 'parameters' and/or 'return_annotation' arguments
3132
+ to override them in the new copy.
3133
+ """
3134
+
3135
+ if parameters is _void:
3136
+ parameters = self.parameters.values()
3137
+
3138
+ if return_annotation is _void:
3139
+ return_annotation = self._return_annotation
3140
+
3141
+ return type(self)(parameters,
3142
+ return_annotation=return_annotation)
3143
+
3144
+ __replace__ = replace
3145
+
3146
+ def _hash_basis(self):
3147
+ params = tuple(param for param in self.parameters.values()
3148
+ if param.kind != _KEYWORD_ONLY)
3149
+
3150
+ kwo_params = {param.name: param for param in self.parameters.values()
3151
+ if param.kind == _KEYWORD_ONLY}
3152
+
3153
+ return params, kwo_params, self.return_annotation
3154
+
3155
+ def __hash__(self):
3156
+ params, kwo_params, return_annotation = self._hash_basis()
3157
+ kwo_params = frozenset(kwo_params.values())
3158
+ return hash((params, kwo_params, return_annotation))
3159
+
3160
+ def __eq__(self, other):
3161
+ if self is other:
3162
+ return True
3163
+ if not isinstance(other, Signature):
3164
+ return NotImplemented
3165
+ return self._hash_basis() == other._hash_basis()
3166
+
3167
+ def _bind(self, args, kwargs, *, partial=False):
3168
+ """Private method. Don't use directly."""
3169
+
3170
+ arguments = {}
3171
+
3172
+ parameters = iter(self.parameters.values())
3173
+ parameters_ex = ()
3174
+ arg_vals = iter(args)
3175
+
3176
+ pos_only_param_in_kwargs = []
3177
+
3178
+ while True:
3179
+ # Let's iterate through the positional arguments and corresponding
3180
+ # parameters
3181
+ try:
3182
+ arg_val = next(arg_vals)
3183
+ except StopIteration:
3184
+ # No more positional arguments
3185
+ try:
3186
+ param = next(parameters)
3187
+ except StopIteration:
3188
+ # No more parameters. That's it. Just need to check that
3189
+ # we have no `kwargs` after this while loop
3190
+ break
3191
+ else:
3192
+ if param.kind == _VAR_POSITIONAL:
3193
+ # That's OK, just empty *args. Let's start parsing
3194
+ # kwargs
3195
+ break
3196
+ elif param.name in kwargs:
3197
+ if param.kind == _POSITIONAL_ONLY:
3198
+ if param.default is _empty:
3199
+ msg = f'missing a required positional-only argument: {param.name!r}'
3200
+ raise TypeError(msg)
3201
+ # Raise a TypeError once we are sure there is no
3202
+ # **kwargs param later.
3203
+ pos_only_param_in_kwargs.append(param)
3204
+ continue
3205
+ parameters_ex = (param,)
3206
+ break
3207
+ elif (param.kind == _VAR_KEYWORD or
3208
+ param.default is not _empty):
3209
+ # That's fine too - we have a default value for this
3210
+ # parameter. So, lets start parsing `kwargs`, starting
3211
+ # with the current parameter
3212
+ parameters_ex = (param,)
3213
+ break
3214
+ else:
3215
+ # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
3216
+ # not in `kwargs`
3217
+ if partial:
3218
+ parameters_ex = (param,)
3219
+ break
3220
+ else:
3221
+ if param.kind == _KEYWORD_ONLY:
3222
+ argtype = ' keyword-only'
3223
+ else:
3224
+ argtype = ''
3225
+ msg = 'missing a required{argtype} argument: {arg!r}'
3226
+ msg = msg.format(arg=param.name, argtype=argtype)
3227
+ raise TypeError(msg) from None
3228
+ else:
3229
+ # We have a positional argument to process
3230
+ try:
3231
+ param = next(parameters)
3232
+ except StopIteration:
3233
+ raise TypeError('too many positional arguments') from None
3234
+ else:
3235
+ if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
3236
+ # Looks like we have no parameter for this positional
3237
+ # argument
3238
+ raise TypeError(
3239
+ 'too many positional arguments') from None
3240
+
3241
+ if param.kind == _VAR_POSITIONAL:
3242
+ # We have an '*args'-like argument, let's fill it with
3243
+ # all positional arguments we have left and move on to
3244
+ # the next phase
3245
+ values = [arg_val]
3246
+ values.extend(arg_vals)
3247
+ arguments[param.name] = tuple(values)
3248
+ break
3249
+
3250
+ if param.name in kwargs and param.kind != _POSITIONAL_ONLY:
3251
+ raise TypeError(
3252
+ 'multiple values for argument {arg!r}'.format(
3253
+ arg=param.name)) from None
3254
+
3255
+ arguments[param.name] = arg_val
3256
+
3257
+ # Now, we iterate through the remaining parameters to process
3258
+ # keyword arguments
3259
+ kwargs_param = None
3260
+ for param in itertools.chain(parameters_ex, parameters):
3261
+ if param.kind == _VAR_KEYWORD:
3262
+ # Memorize that we have a '**kwargs'-like parameter
3263
+ kwargs_param = param
3264
+ continue
3265
+
3266
+ if param.kind == _VAR_POSITIONAL:
3267
+ # Named arguments don't refer to '*args'-like parameters.
3268
+ # We only arrive here if the positional arguments ended
3269
+ # before reaching the last parameter before *args.
3270
+ continue
3271
+
3272
+ param_name = param.name
3273
+ try:
3274
+ arg_val = kwargs.pop(param_name)
3275
+ except KeyError:
3276
+ # We have no value for this parameter. It's fine though,
3277
+ # if it has a default value, or it is an '*args'-like
3278
+ # parameter, left alone by the processing of positional
3279
+ # arguments.
3280
+ if (not partial and param.kind != _VAR_POSITIONAL and
3281
+ param.default is _empty):
3282
+ raise TypeError('missing a required argument: {arg!r}'. \
3283
+ format(arg=param_name)) from None
3284
+
3285
+ else:
3286
+ arguments[param_name] = arg_val
3287
+
3288
+ if kwargs:
3289
+ if kwargs_param is not None:
3290
+ # Process our '**kwargs'-like parameter
3291
+ arguments[kwargs_param.name] = kwargs
3292
+ elif pos_only_param_in_kwargs:
3293
+ raise TypeError(
3294
+ 'got some positional-only arguments passed as '
3295
+ 'keyword arguments: {arg!r}'.format(
3296
+ arg=', '.join(
3297
+ param.name
3298
+ for param in pos_only_param_in_kwargs
3299
+ ),
3300
+ ),
3301
+ )
3302
+ else:
3303
+ raise TypeError(
3304
+ 'got an unexpected keyword argument {arg!r}'.format(
3305
+ arg=next(iter(kwargs))))
3306
+
3307
+ return self._bound_arguments_cls(self, arguments)
3308
+
3309
+ def bind(self, /, *args, **kwargs):
3310
+ """Get a BoundArguments object, that maps the passed `args`
3311
+ and `kwargs` to the function's signature. Raises `TypeError`
3312
+ if the passed arguments can not be bound.
3313
+ """
3314
+ return self._bind(args, kwargs)
3315
+
3316
+ def bind_partial(self, /, *args, **kwargs):
3317
+ """Get a BoundArguments object, that partially maps the
3318
+ passed `args` and `kwargs` to the function's signature.
3319
+ Raises `TypeError` if the passed arguments can not be bound.
3320
+ """
3321
+ return self._bind(args, kwargs, partial=True)
3322
+
3323
+ def __reduce__(self):
3324
+ return (type(self),
3325
+ (tuple(self._parameters.values()),),
3326
+ {'_return_annotation': self._return_annotation})
3327
+
3328
+ def __setstate__(self, state):
3329
+ self._return_annotation = state['_return_annotation']
3330
+
3331
+ def __repr__(self):
3332
+ return '<{} {}>'.format(self.__class__.__name__, self)
3333
+
3334
+ def __str__(self):
3335
+ return self.format()
3336
+
3337
+ def format(self, *, max_width=None):
3338
+ """Create a string representation of the Signature object.
3339
+
3340
+ If *max_width* integer is passed,
3341
+ signature will try to fit into the *max_width*.
3342
+ If signature is longer than *max_width*,
3343
+ all parameters will be on separate lines.
3344
+ """
3345
+ result = []
3346
+ render_pos_only_separator = False
3347
+ render_kw_only_separator = True
3348
+ for param in self.parameters.values():
3349
+ formatted = str(param)
3350
+
3351
+ kind = param.kind
3352
+
3353
+ if kind == _POSITIONAL_ONLY:
3354
+ render_pos_only_separator = True
3355
+ elif render_pos_only_separator:
3356
+ # It's not a positional-only parameter, and the flag
3357
+ # is set to 'True' (there were pos-only params before.)
3358
+ result.append('/')
3359
+ render_pos_only_separator = False
3360
+
3361
+ if kind == _VAR_POSITIONAL:
3362
+ # OK, we have an '*args'-like parameter, so we won't need
3363
+ # a '*' to separate keyword-only arguments
3364
+ render_kw_only_separator = False
3365
+ elif kind == _KEYWORD_ONLY and render_kw_only_separator:
3366
+ # We have a keyword-only parameter to render and we haven't
3367
+ # rendered an '*args'-like parameter before, so add a '*'
3368
+ # separator to the parameters list ("foo(arg1, *, arg2)" case)
3369
+ result.append('*')
3370
+ # This condition should be only triggered once, so
3371
+ # reset the flag
3372
+ render_kw_only_separator = False
3373
+
3374
+ result.append(formatted)
3375
+
3376
+ if render_pos_only_separator:
3377
+ # There were only positional-only parameters, hence the
3378
+ # flag was not reset to 'False'
3379
+ result.append('/')
3380
+
3381
+ rendered = '({})'.format(', '.join(result))
3382
+ if max_width is not None and len(rendered) > max_width:
3383
+ rendered = '(\n {}\n)'.format(',\n '.join(result))
3384
+
3385
+ if self.return_annotation is not _empty:
3386
+ anno = formatannotation(self.return_annotation)
3387
+ rendered += ' -> {}'.format(anno)
3388
+
3389
+ return rendered
3390
+
3391
+
3392
+ def signature(obj, *, follow_wrapped=True, globals=None, locals=None, eval_str=False):
3393
+ """Get a signature object for the passed callable."""
3394
+ return Signature.from_callable(obj, follow_wrapped=follow_wrapped,
3395
+ globals=globals, locals=locals, eval_str=eval_str)
3396
+
3397
+
3398
+ class BufferFlags(enum.IntFlag):
3399
+ SIMPLE = 0x0
3400
+ WRITABLE = 0x1
3401
+ FORMAT = 0x4
3402
+ ND = 0x8
3403
+ STRIDES = 0x10 | ND
3404
+ C_CONTIGUOUS = 0x20 | STRIDES
3405
+ F_CONTIGUOUS = 0x40 | STRIDES
3406
+ ANY_CONTIGUOUS = 0x80 | STRIDES
3407
+ INDIRECT = 0x100 | STRIDES
3408
+ CONTIG = ND | WRITABLE
3409
+ CONTIG_RO = ND
3410
+ STRIDED = STRIDES | WRITABLE
3411
+ STRIDED_RO = STRIDES
3412
+ RECORDS = STRIDES | WRITABLE | FORMAT
3413
+ RECORDS_RO = STRIDES | FORMAT
3414
+ FULL = INDIRECT | WRITABLE | FORMAT
3415
+ FULL_RO = INDIRECT | FORMAT
3416
+ READ = 0x100
3417
+ WRITE = 0x200
3418
+
3419
+
3420
+ def _main():
3421
+ """ Logic for inspecting an object given at command line """
3422
+ import argparse
3423
+ import importlib
3424
+
3425
+ parser = argparse.ArgumentParser()
3426
+ parser.add_argument(
3427
+ 'object',
3428
+ help="The object to be analysed. "
3429
+ "It supports the 'module:qualname' syntax")
3430
+ parser.add_argument(
3431
+ '-d', '--details', action='store_true',
3432
+ help='Display info about the module rather than its source code')
3433
+
3434
+ args = parser.parse_args()
3435
+
3436
+ target = args.object
3437
+ mod_name, has_attrs, attrs = target.partition(":")
3438
+ try:
3439
+ obj = module = importlib.import_module(mod_name)
3440
+ except Exception as exc:
3441
+ msg = "Failed to import {} ({}: {})".format(mod_name,
3442
+ type(exc).__name__,
3443
+ exc)
3444
+ print(msg, file=sys.stderr)
3445
+ sys.exit(2)
3446
+
3447
+ if has_attrs:
3448
+ parts = attrs.split(".")
3449
+ obj = module
3450
+ for part in parts:
3451
+ obj = getattr(obj, part)
3452
+
3453
+ if module.__name__ in sys.builtin_module_names:
3454
+ print("Can't get info for builtin modules.", file=sys.stderr)
3455
+ sys.exit(1)
3456
+
3457
+ if args.details:
3458
+ print('Target: {}'.format(target))
3459
+ print('Origin: {}'.format(getsourcefile(module)))
3460
+ print('Cached: {}'.format(module.__cached__))
3461
+ if obj is module:
3462
+ print('Loader: {}'.format(repr(module.__loader__)))
3463
+ if hasattr(module, '__path__'):
3464
+ print('Submodule search path: {}'.format(module.__path__))
3465
+ else:
3466
+ try:
3467
+ __, lineno = findsource(obj)
3468
+ except Exception:
3469
+ pass
3470
+ else:
3471
+ print('Line: {}'.format(lineno))
3472
+
3473
+ print('\n')
3474
+ else:
3475
+ print(getsource(obj))
3476
+
3477
+
3478
+ if __name__ == "__main__":
3479
+ _main()