mypy-dev 1.9.0.dev0__py3-none-any.whl

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 (1018) hide show
  1. mypy/__init__.py +1 -0
  2. mypy/__main__.py +37 -0
  3. mypy/api.py +94 -0
  4. mypy/applytype.py +156 -0
  5. mypy/argmap.py +268 -0
  6. mypy/binder.py +538 -0
  7. mypy/bogus_type.py +27 -0
  8. mypy/build.py +3562 -0
  9. mypy/checker.py +8372 -0
  10. mypy/checkexpr.py +6615 -0
  11. mypy/checkmember.py +1356 -0
  12. mypy/checkpattern.py +801 -0
  13. mypy/checkstrformat.py +1109 -0
  14. mypy/config_parser.py +670 -0
  15. mypy/constant_fold.py +187 -0
  16. mypy/constraints.py +1624 -0
  17. mypy/copytype.py +133 -0
  18. mypy/defaults.py +46 -0
  19. mypy/dmypy/__init__.py +0 -0
  20. mypy/dmypy/__main__.py +6 -0
  21. mypy/dmypy/client.py +749 -0
  22. mypy/dmypy_os.py +42 -0
  23. mypy/dmypy_server.py +1107 -0
  24. mypy/dmypy_util.py +117 -0
  25. mypy/erasetype.py +278 -0
  26. mypy/errorcodes.py +285 -0
  27. mypy/errors.py +1280 -0
  28. mypy/evalexpr.py +205 -0
  29. mypy/expandtype.py +510 -0
  30. mypy/exprtotype.py +206 -0
  31. mypy/fastparse.py +2147 -0
  32. mypy/find_sources.py +243 -0
  33. mypy/fixup.py +426 -0
  34. mypy/freetree.py +23 -0
  35. mypy/fscache.py +309 -0
  36. mypy/fswatcher.py +106 -0
  37. mypy/gclogger.py +47 -0
  38. mypy/git.py +34 -0
  39. mypy/graph_utils.py +112 -0
  40. mypy/indirection.py +121 -0
  41. mypy/infer.py +75 -0
  42. mypy/inspections.py +627 -0
  43. mypy/ipc.py +310 -0
  44. mypy/join.py +866 -0
  45. mypy/literals.py +306 -0
  46. mypy/lookup.py +61 -0
  47. mypy/main.py +1574 -0
  48. mypy/maptype.py +106 -0
  49. mypy/meet.py +1140 -0
  50. mypy/memprofile.py +121 -0
  51. mypy/message_registry.py +326 -0
  52. mypy/messages.py +3171 -0
  53. mypy/metastore.py +225 -0
  54. mypy/mixedtraverser.py +112 -0
  55. mypy/modulefinder.py +875 -0
  56. mypy/moduleinspect.py +184 -0
  57. mypy/mro.py +62 -0
  58. mypy/nodes.py +4112 -0
  59. mypy/operators.py +126 -0
  60. mypy/options.py +556 -0
  61. mypy/parse.py +30 -0
  62. mypy/partially_defined.py +675 -0
  63. mypy/patterns.py +150 -0
  64. mypy/plugin.py +901 -0
  65. mypy/plugins/__init__.py +0 -0
  66. mypy/plugins/attrs.py +1152 -0
  67. mypy/plugins/common.py +440 -0
  68. mypy/plugins/ctypes.py +245 -0
  69. mypy/plugins/dataclasses.py +1101 -0
  70. mypy/plugins/default.py +518 -0
  71. mypy/plugins/enums.py +259 -0
  72. mypy/plugins/functools.py +104 -0
  73. mypy/plugins/proper_plugin.py +175 -0
  74. mypy/plugins/singledispatch.py +224 -0
  75. mypy/py.typed +1 -0
  76. mypy/pyinfo.py +78 -0
  77. mypy/reachability.py +362 -0
  78. mypy/refinfo.py +92 -0
  79. mypy/renaming.py +568 -0
  80. mypy/report.py +924 -0
  81. mypy/scope.py +125 -0
  82. mypy/semanal.py +7023 -0
  83. mypy/semanal_classprop.py +187 -0
  84. mypy/semanal_enum.py +253 -0
  85. mypy/semanal_infer.py +128 -0
  86. mypy/semanal_main.py +511 -0
  87. mypy/semanal_namedtuple.py +670 -0
  88. mypy/semanal_newtype.py +273 -0
  89. mypy/semanal_pass1.py +156 -0
  90. mypy/semanal_shared.py +490 -0
  91. mypy/semanal_typeargs.py +265 -0
  92. mypy/semanal_typeddict.py +575 -0
  93. mypy/server/__init__.py +0 -0
  94. mypy/server/astdiff.py +518 -0
  95. mypy/server/astmerge.py +562 -0
  96. mypy/server/aststrip.py +281 -0
  97. mypy/server/deps.py +1137 -0
  98. mypy/server/mergecheck.py +83 -0
  99. mypy/server/objgraph.py +101 -0
  100. mypy/server/subexpr.py +198 -0
  101. mypy/server/target.py +11 -0
  102. mypy/server/trigger.py +26 -0
  103. mypy/server/update.py +1339 -0
  104. mypy/sharedparse.py +112 -0
  105. mypy/solve.py +562 -0
  106. mypy/split_namespace.py +35 -0
  107. mypy/state.py +28 -0
  108. mypy/stats.py +489 -0
  109. mypy/strconv.py +641 -0
  110. mypy/stubdoc.py +491 -0
  111. mypy/stubgen.py +1873 -0
  112. mypy/stubgenc.py +993 -0
  113. mypy/stubinfo.py +173 -0
  114. mypy/stubtest.py +2079 -0
  115. mypy/stubutil.py +807 -0
  116. mypy/subtypes.py +1967 -0
  117. mypy/suggestions.py +1046 -0
  118. mypy/test/__init__.py +0 -0
  119. mypy/test/config.py +28 -0
  120. mypy/test/data.py +823 -0
  121. mypy/test/helpers.py +476 -0
  122. mypy/test/meta/__init__.py +0 -0
  123. mypy/test/meta/_pytest.py +72 -0
  124. mypy/test/meta/test_diff_helper.py +47 -0
  125. mypy/test/meta/test_parse_data.py +73 -0
  126. mypy/test/meta/test_update_data.py +135 -0
  127. mypy/test/test_find_sources.py +376 -0
  128. mypy/test/test_ref_info.py +45 -0
  129. mypy/test/testapi.py +45 -0
  130. mypy/test/testargs.py +77 -0
  131. mypy/test/testcheck.py +322 -0
  132. mypy/test/testcmdline.py +152 -0
  133. mypy/test/testconstraints.py +134 -0
  134. mypy/test/testdaemon.py +132 -0
  135. mypy/test/testdeps.py +77 -0
  136. mypy/test/testdiff.py +67 -0
  137. mypy/test/testerrorstream.py +46 -0
  138. mypy/test/testfinegrained.py +438 -0
  139. mypy/test/testfinegrainedcache.py +18 -0
  140. mypy/test/testformatter.py +85 -0
  141. mypy/test/testfscache.py +101 -0
  142. mypy/test/testgraph.py +83 -0
  143. mypy/test/testinfer.py +373 -0
  144. mypy/test/testipc.py +119 -0
  145. mypy/test/testmerge.py +238 -0
  146. mypy/test/testmodulefinder.py +278 -0
  147. mypy/test/testmypyc.py +14 -0
  148. mypy/test/testparse.py +107 -0
  149. mypy/test/testpep561.py +211 -0
  150. mypy/test/testpythoneval.py +117 -0
  151. mypy/test/testreports.py +55 -0
  152. mypy/test/testsemanal.py +209 -0
  153. mypy/test/testsolve.py +285 -0
  154. mypy/test/teststubgen.py +1412 -0
  155. mypy/test/teststubinfo.py +12 -0
  156. mypy/test/teststubtest.py +2492 -0
  157. mypy/test/testsubtypes.py +303 -0
  158. mypy/test/testtransform.py +64 -0
  159. mypy/test/testtypegen.py +83 -0
  160. mypy/test/testtypes.py +1551 -0
  161. mypy/test/testutil.py +111 -0
  162. mypy/test/typefixture.py +415 -0
  163. mypy/test/update_data.py +87 -0
  164. mypy/test/visitors.py +63 -0
  165. mypy/traverser.py +961 -0
  166. mypy/treetransform.py +800 -0
  167. mypy/tvar_scope.py +147 -0
  168. mypy/type_visitor.py +564 -0
  169. mypy/typeanal.py +2510 -0
  170. mypy/typeops.py +1082 -0
  171. mypy/types.py +3686 -0
  172. mypy/types_utils.py +166 -0
  173. mypy/typeshed/LICENSE +237 -0
  174. mypy/typeshed/stdlib/VERSIONS +308 -0
  175. mypy/typeshed/stdlib/__future__.pyi +36 -0
  176. mypy/typeshed/stdlib/__main__.pyi +3 -0
  177. mypy/typeshed/stdlib/_ast.pyi +587 -0
  178. mypy/typeshed/stdlib/_bisect.pyi +84 -0
  179. mypy/typeshed/stdlib/_bootlocale.pyi +1 -0
  180. mypy/typeshed/stdlib/_codecs.pyi +133 -0
  181. mypy/typeshed/stdlib/_collections_abc.pyi +94 -0
  182. mypy/typeshed/stdlib/_compat_pickle.pyi +8 -0
  183. mypy/typeshed/stdlib/_compression.pyi +25 -0
  184. mypy/typeshed/stdlib/_csv.pyi +90 -0
  185. mypy/typeshed/stdlib/_ctypes.pyi +205 -0
  186. mypy/typeshed/stdlib/_curses.pyi +557 -0
  187. mypy/typeshed/stdlib/_decimal.pyi +281 -0
  188. mypy/typeshed/stdlib/_dummy_thread.pyi +27 -0
  189. mypy/typeshed/stdlib/_dummy_threading.pyi +164 -0
  190. mypy/typeshed/stdlib/_heapq.pyi +11 -0
  191. mypy/typeshed/stdlib/_imp.pyi +28 -0
  192. mypy/typeshed/stdlib/_json.pyi +49 -0
  193. mypy/typeshed/stdlib/_locale.pyi +100 -0
  194. mypy/typeshed/stdlib/_markupbase.pyi +16 -0
  195. mypy/typeshed/stdlib/_msi.pyi +91 -0
  196. mypy/typeshed/stdlib/_operator.pyi +147 -0
  197. mypy/typeshed/stdlib/_osx_support.pyi +34 -0
  198. mypy/typeshed/stdlib/_posixsubprocess.pyi +32 -0
  199. mypy/typeshed/stdlib/_py_abc.pyi +14 -0
  200. mypy/typeshed/stdlib/_pydecimal.pyi +43 -0
  201. mypy/typeshed/stdlib/_random.pyi +12 -0
  202. mypy/typeshed/stdlib/_sitebuiltins.pyi +16 -0
  203. mypy/typeshed/stdlib/_socket.pyi +802 -0
  204. mypy/typeshed/stdlib/_stat.pyi +103 -0
  205. mypy/typeshed/stdlib/_thread.pyi +52 -0
  206. mypy/typeshed/stdlib/_threading_local.pyi +17 -0
  207. mypy/typeshed/stdlib/_tkinter.pyi +120 -0
  208. mypy/typeshed/stdlib/_tracemalloc.pyi +17 -0
  209. mypy/typeshed/stdlib/_typeshed/__init__.pyi +347 -0
  210. mypy/typeshed/stdlib/_typeshed/dbapi.pyi +37 -0
  211. mypy/typeshed/stdlib/_typeshed/wsgi.pyi +44 -0
  212. mypy/typeshed/stdlib/_typeshed/xml.pyi +9 -0
  213. mypy/typeshed/stdlib/_warnings.pyi +55 -0
  214. mypy/typeshed/stdlib/_weakref.pyi +41 -0
  215. mypy/typeshed/stdlib/_weakrefset.pyi +51 -0
  216. mypy/typeshed/stdlib/_winapi.pyi +251 -0
  217. mypy/typeshed/stdlib/abc.pyi +49 -0
  218. mypy/typeshed/stdlib/aifc.pyi +91 -0
  219. mypy/typeshed/stdlib/antigravity.pyi +3 -0
  220. mypy/typeshed/stdlib/argparse.pyi +571 -0
  221. mypy/typeshed/stdlib/array.pyi +92 -0
  222. mypy/typeshed/stdlib/ast.pyi +277 -0
  223. mypy/typeshed/stdlib/asynchat.pyi +21 -0
  224. mypy/typeshed/stdlib/asyncio/__init__.pyi +41 -0
  225. mypy/typeshed/stdlib/asyncio/base_events.pyi +440 -0
  226. mypy/typeshed/stdlib/asyncio/base_futures.pyi +19 -0
  227. mypy/typeshed/stdlib/asyncio/base_subprocess.pyi +63 -0
  228. mypy/typeshed/stdlib/asyncio/base_tasks.pyi +9 -0
  229. mypy/typeshed/stdlib/asyncio/constants.pyi +20 -0
  230. mypy/typeshed/stdlib/asyncio/coroutines.pyi +26 -0
  231. mypy/typeshed/stdlib/asyncio/events.pyi +574 -0
  232. mypy/typeshed/stdlib/asyncio/exceptions.pyi +43 -0
  233. mypy/typeshed/stdlib/asyncio/format_helpers.pyi +20 -0
  234. mypy/typeshed/stdlib/asyncio/futures.pyi +57 -0
  235. mypy/typeshed/stdlib/asyncio/locks.pyi +121 -0
  236. mypy/typeshed/stdlib/asyncio/log.pyi +3 -0
  237. mypy/typeshed/stdlib/asyncio/mixins.pyi +9 -0
  238. mypy/typeshed/stdlib/asyncio/proactor_events.pyi +64 -0
  239. mypy/typeshed/stdlib/asyncio/protocols.pyi +34 -0
  240. mypy/typeshed/stdlib/asyncio/queues.pyi +47 -0
  241. mypy/typeshed/stdlib/asyncio/runners.pyi +32 -0
  242. mypy/typeshed/stdlib/asyncio/selector_events.pyi +8 -0
  243. mypy/typeshed/stdlib/asyncio/sslproto.pyi +163 -0
  244. mypy/typeshed/stdlib/asyncio/staggered.pyi +10 -0
  245. mypy/typeshed/stdlib/asyncio/streams.pyi +148 -0
  246. mypy/typeshed/stdlib/asyncio/subprocess.pyi +229 -0
  247. mypy/typeshed/stdlib/asyncio/taskgroups.pyi +25 -0
  248. mypy/typeshed/stdlib/asyncio/tasks.pyi +477 -0
  249. mypy/typeshed/stdlib/asyncio/threads.pyi +9 -0
  250. mypy/typeshed/stdlib/asyncio/timeouts.pyi +19 -0
  251. mypy/typeshed/stdlib/asyncio/transports.pyi +47 -0
  252. mypy/typeshed/stdlib/asyncio/trsock.pyi +98 -0
  253. mypy/typeshed/stdlib/asyncio/unix_events.pyi +173 -0
  254. mypy/typeshed/stdlib/asyncio/windows_events.pyi +83 -0
  255. mypy/typeshed/stdlib/asyncio/windows_utils.pyi +49 -0
  256. mypy/typeshed/stdlib/asyncore.pyi +90 -0
  257. mypy/typeshed/stdlib/atexit.pyi +12 -0
  258. mypy/typeshed/stdlib/audioop.pyi +42 -0
  259. mypy/typeshed/stdlib/base64.pyi +59 -0
  260. mypy/typeshed/stdlib/bdb.pyi +102 -0
  261. mypy/typeshed/stdlib/binascii.pyi +36 -0
  262. mypy/typeshed/stdlib/binhex.pyi +45 -0
  263. mypy/typeshed/stdlib/bisect.pyi +4 -0
  264. mypy/typeshed/stdlib/builtins.pyi +1937 -0
  265. mypy/typeshed/stdlib/bz2.pyi +146 -0
  266. mypy/typeshed/stdlib/cProfile.pyi +35 -0
  267. mypy/typeshed/stdlib/calendar.pyi +206 -0
  268. mypy/typeshed/stdlib/cgi.pyi +118 -0
  269. mypy/typeshed/stdlib/cgitb.pyi +32 -0
  270. mypy/typeshed/stdlib/chunk.pyi +20 -0
  271. mypy/typeshed/stdlib/cmath.pyi +36 -0
  272. mypy/typeshed/stdlib/cmd.pyi +45 -0
  273. mypy/typeshed/stdlib/code.pyi +33 -0
  274. mypy/typeshed/stdlib/codecs.pyi +285 -0
  275. mypy/typeshed/stdlib/codeop.pyi +13 -0
  276. mypy/typeshed/stdlib/collections/__init__.pyi +477 -0
  277. mypy/typeshed/stdlib/collections/abc.pyi +2 -0
  278. mypy/typeshed/stdlib/colorsys.pyi +13 -0
  279. mypy/typeshed/stdlib/compileall.pyi +111 -0
  280. mypy/typeshed/stdlib/concurrent/__init__.pyi +0 -0
  281. mypy/typeshed/stdlib/concurrent/futures/__init__.pyi +32 -0
  282. mypy/typeshed/stdlib/concurrent/futures/_base.pyi +120 -0
  283. mypy/typeshed/stdlib/concurrent/futures/process.pyi +233 -0
  284. mypy/typeshed/stdlib/concurrent/futures/thread.pyi +80 -0
  285. mypy/typeshed/stdlib/configparser.pyi +313 -0
  286. mypy/typeshed/stdlib/contextlib.pyi +207 -0
  287. mypy/typeshed/stdlib/contextvars.pyi +63 -0
  288. mypy/typeshed/stdlib/copy.pyi +16 -0
  289. mypy/typeshed/stdlib/copyreg.pyi +21 -0
  290. mypy/typeshed/stdlib/crypt.pyi +12 -0
  291. mypy/typeshed/stdlib/csv.pyi +147 -0
  292. mypy/typeshed/stdlib/ctypes/__init__.pyi +187 -0
  293. mypy/typeshed/stdlib/ctypes/_endian.pyi +19 -0
  294. mypy/typeshed/stdlib/ctypes/util.pyi +6 -0
  295. mypy/typeshed/stdlib/ctypes/wintypes.pyi +298 -0
  296. mypy/typeshed/stdlib/curses/__init__.pyi +21 -0
  297. mypy/typeshed/stdlib/curses/ascii.pyi +63 -0
  298. mypy/typeshed/stdlib/curses/has_key.pyi +4 -0
  299. mypy/typeshed/stdlib/curses/panel.pyi +25 -0
  300. mypy/typeshed/stdlib/curses/textpad.pyi +13 -0
  301. mypy/typeshed/stdlib/dataclasses.pyi +313 -0
  302. mypy/typeshed/stdlib/datetime.pyi +295 -0
  303. mypy/typeshed/stdlib/dbm/__init__.pyi +95 -0
  304. mypy/typeshed/stdlib/dbm/dumb.pyi +31 -0
  305. mypy/typeshed/stdlib/dbm/gnu.pyi +40 -0
  306. mypy/typeshed/stdlib/dbm/ndbm.pyi +36 -0
  307. mypy/typeshed/stdlib/decimal.pyi +2 -0
  308. mypy/typeshed/stdlib/difflib.pyi +140 -0
  309. mypy/typeshed/stdlib/dis.pyi +144 -0
  310. mypy/typeshed/stdlib/distutils/__init__.pyi +5 -0
  311. mypy/typeshed/stdlib/distutils/archive_util.pyi +20 -0
  312. mypy/typeshed/stdlib/distutils/bcppcompiler.pyi +3 -0
  313. mypy/typeshed/stdlib/distutils/ccompiler.pyi +152 -0
  314. mypy/typeshed/stdlib/distutils/cmd.pyi +66 -0
  315. mypy/typeshed/stdlib/distutils/command/__init__.pyi +0 -0
  316. mypy/typeshed/stdlib/distutils/command/bdist.pyi +25 -0
  317. mypy/typeshed/stdlib/distutils/command/bdist_dumb.pyi +21 -0
  318. mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi +45 -0
  319. mypy/typeshed/stdlib/distutils/command/bdist_packager.pyi +0 -0
  320. mypy/typeshed/stdlib/distutils/command/bdist_rpm.pyi +52 -0
  321. mypy/typeshed/stdlib/distutils/command/bdist_wininst.pyi +16 -0
  322. mypy/typeshed/stdlib/distutils/command/build.pyi +31 -0
  323. mypy/typeshed/stdlib/distutils/command/build_clib.pyi +27 -0
  324. mypy/typeshed/stdlib/distutils/command/build_ext.pyi +50 -0
  325. mypy/typeshed/stdlib/distutils/command/build_py.pyi +44 -0
  326. mypy/typeshed/stdlib/distutils/command/build_scripts.pyi +24 -0
  327. mypy/typeshed/stdlib/distutils/command/check.pyi +39 -0
  328. mypy/typeshed/stdlib/distutils/command/clean.pyi +17 -0
  329. mypy/typeshed/stdlib/distutils/command/config.pyi +83 -0
  330. mypy/typeshed/stdlib/distutils/command/install.pyi +63 -0
  331. mypy/typeshed/stdlib/distutils/command/install_data.pyi +19 -0
  332. mypy/typeshed/stdlib/distutils/command/install_egg_info.pyi +18 -0
  333. mypy/typeshed/stdlib/distutils/command/install_headers.pyi +16 -0
  334. mypy/typeshed/stdlib/distutils/command/install_lib.pyi +25 -0
  335. mypy/typeshed/stdlib/distutils/command/install_scripts.pyi +18 -0
  336. mypy/typeshed/stdlib/distutils/command/register.pyi +18 -0
  337. mypy/typeshed/stdlib/distutils/command/sdist.pyi +42 -0
  338. mypy/typeshed/stdlib/distutils/command/upload.pyi +17 -0
  339. mypy/typeshed/stdlib/distutils/config.pyi +17 -0
  340. mypy/typeshed/stdlib/distutils/core.pyi +57 -0
  341. mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi +20 -0
  342. mypy/typeshed/stdlib/distutils/debug.pyi +1 -0
  343. mypy/typeshed/stdlib/distutils/dep_util.pyi +3 -0
  344. mypy/typeshed/stdlib/distutils/dir_util.pyi +13 -0
  345. mypy/typeshed/stdlib/distutils/dist.pyi +146 -0
  346. mypy/typeshed/stdlib/distutils/errors.pyi +19 -0
  347. mypy/typeshed/stdlib/distutils/extension.pyi +36 -0
  348. mypy/typeshed/stdlib/distutils/fancy_getopt.pyi +34 -0
  349. mypy/typeshed/stdlib/distutils/file_util.pyi +14 -0
  350. mypy/typeshed/stdlib/distutils/filelist.pyi +50 -0
  351. mypy/typeshed/stdlib/distutils/log.pyi +25 -0
  352. mypy/typeshed/stdlib/distutils/msvccompiler.pyi +3 -0
  353. mypy/typeshed/stdlib/distutils/spawn.pyi +2 -0
  354. mypy/typeshed/stdlib/distutils/sysconfig.pyi +22 -0
  355. mypy/typeshed/stdlib/distutils/text_file.pyi +21 -0
  356. mypy/typeshed/stdlib/distutils/unixccompiler.pyi +3 -0
  357. mypy/typeshed/stdlib/distutils/util.pyi +46 -0
  358. mypy/typeshed/stdlib/distutils/version.pyi +36 -0
  359. mypy/typeshed/stdlib/doctest.pyi +248 -0
  360. mypy/typeshed/stdlib/dummy_threading.pyi +2 -0
  361. mypy/typeshed/stdlib/email/__init__.pyi +29 -0
  362. mypy/typeshed/stdlib/email/_header_value_parser.pyi +392 -0
  363. mypy/typeshed/stdlib/email/_policybase.pyi +51 -0
  364. mypy/typeshed/stdlib/email/base64mime.pyi +13 -0
  365. mypy/typeshed/stdlib/email/charset.pyi +34 -0
  366. mypy/typeshed/stdlib/email/contentmanager.pyi +11 -0
  367. mypy/typeshed/stdlib/email/encoders.pyi +8 -0
  368. mypy/typeshed/stdlib/email/errors.pyi +39 -0
  369. mypy/typeshed/stdlib/email/feedparser.pyi +23 -0
  370. mypy/typeshed/stdlib/email/generator.pyi +40 -0
  371. mypy/typeshed/stdlib/email/header.pyi +31 -0
  372. mypy/typeshed/stdlib/email/headerregistry.pyi +178 -0
  373. mypy/typeshed/stdlib/email/iterators.pyi +12 -0
  374. mypy/typeshed/stdlib/email/message.pyi +161 -0
  375. mypy/typeshed/stdlib/email/mime/__init__.pyi +0 -0
  376. mypy/typeshed/stdlib/email/mime/application.pyi +17 -0
  377. mypy/typeshed/stdlib/email/mime/audio.pyi +17 -0
  378. mypy/typeshed/stdlib/email/mime/base.pyi +8 -0
  379. mypy/typeshed/stdlib/email/mime/image.pyi +17 -0
  380. mypy/typeshed/stdlib/email/mime/message.pyi +8 -0
  381. mypy/typeshed/stdlib/email/mime/multipart.pyi +18 -0
  382. mypy/typeshed/stdlib/email/mime/nonmultipart.pyi +5 -0
  383. mypy/typeshed/stdlib/email/mime/text.pyi +9 -0
  384. mypy/typeshed/stdlib/email/parser.pyi +26 -0
  385. mypy/typeshed/stdlib/email/policy.pyi +38 -0
  386. mypy/typeshed/stdlib/email/quoprimime.pyi +28 -0
  387. mypy/typeshed/stdlib/email/utils.pyi +66 -0
  388. mypy/typeshed/stdlib/encodings/__init__.pyi +10 -0
  389. mypy/typeshed/stdlib/encodings/utf_8.pyi +21 -0
  390. mypy/typeshed/stdlib/encodings/utf_8_sig.pyi +22 -0
  391. mypy/typeshed/stdlib/ensurepip/__init__.pyi +12 -0
  392. mypy/typeshed/stdlib/enum.pyi +317 -0
  393. mypy/typeshed/stdlib/errno.pyi +222 -0
  394. mypy/typeshed/stdlib/faulthandler.pyi +13 -0
  395. mypy/typeshed/stdlib/fcntl.pyi +127 -0
  396. mypy/typeshed/stdlib/filecmp.pyi +57 -0
  397. mypy/typeshed/stdlib/fileinput.pyi +213 -0
  398. mypy/typeshed/stdlib/fnmatch.pyi +9 -0
  399. mypy/typeshed/stdlib/formatter.pyi +88 -0
  400. mypy/typeshed/stdlib/fractions.pyi +150 -0
  401. mypy/typeshed/stdlib/ftplib.pyi +178 -0
  402. mypy/typeshed/stdlib/functools.pyi +200 -0
  403. mypy/typeshed/stdlib/gc.pyi +37 -0
  404. mypy/typeshed/stdlib/genericpath.pyi +52 -0
  405. mypy/typeshed/stdlib/getopt.pyi +11 -0
  406. mypy/typeshed/stdlib/getpass.pyi +8 -0
  407. mypy/typeshed/stdlib/gettext.pyi +169 -0
  408. mypy/typeshed/stdlib/glob.pyi +42 -0
  409. mypy/typeshed/stdlib/graphlib.pyi +28 -0
  410. mypy/typeshed/stdlib/grp.pyi +21 -0
  411. mypy/typeshed/stdlib/gzip.pyi +160 -0
  412. mypy/typeshed/stdlib/hashlib.pyi +165 -0
  413. mypy/typeshed/stdlib/heapq.pyi +17 -0
  414. mypy/typeshed/stdlib/hmac.pyi +38 -0
  415. mypy/typeshed/stdlib/html/__init__.pyi +6 -0
  416. mypy/typeshed/stdlib/html/entities.pyi +6 -0
  417. mypy/typeshed/stdlib/html/parser.pyi +34 -0
  418. mypy/typeshed/stdlib/http/__init__.pyi +105 -0
  419. mypy/typeshed/stdlib/http/client.pyi +259 -0
  420. mypy/typeshed/stdlib/http/cookiejar.pyi +159 -0
  421. mypy/typeshed/stdlib/http/cookies.pyi +60 -0
  422. mypy/typeshed/stdlib/http/server.pyi +83 -0
  423. mypy/typeshed/stdlib/imaplib.pyi +168 -0
  424. mypy/typeshed/stdlib/imghdr.pyi +17 -0
  425. mypy/typeshed/stdlib/imp.pyi +62 -0
  426. mypy/typeshed/stdlib/importlib/__init__.pyi +24 -0
  427. mypy/typeshed/stdlib/importlib/_abc.pyi +15 -0
  428. mypy/typeshed/stdlib/importlib/abc.pyi +172 -0
  429. mypy/typeshed/stdlib/importlib/machinery.pyi +179 -0
  430. mypy/typeshed/stdlib/importlib/metadata/__init__.pyi +276 -0
  431. mypy/typeshed/stdlib/importlib/metadata/_meta.pyi +40 -0
  432. mypy/typeshed/stdlib/importlib/readers.pyi +68 -0
  433. mypy/typeshed/stdlib/importlib/resources/__init__.pyi +46 -0
  434. mypy/typeshed/stdlib/importlib/resources/abc.pyi +12 -0
  435. mypy/typeshed/stdlib/importlib/resources/readers.pyi +14 -0
  436. mypy/typeshed/stdlib/importlib/resources/simple.pyi +49 -0
  437. mypy/typeshed/stdlib/importlib/simple.pyi +11 -0
  438. mypy/typeshed/stdlib/importlib/util.pyi +43 -0
  439. mypy/typeshed/stdlib/inspect.pyi +631 -0
  440. mypy/typeshed/stdlib/io.pyi +204 -0
  441. mypy/typeshed/stdlib/ipaddress.pyi +208 -0
  442. mypy/typeshed/stdlib/itertools.pyi +293 -0
  443. mypy/typeshed/stdlib/json/__init__.pyi +61 -0
  444. mypy/typeshed/stdlib/json/decoder.pyi +32 -0
  445. mypy/typeshed/stdlib/json/encoder.pyi +38 -0
  446. mypy/typeshed/stdlib/json/tool.pyi +1 -0
  447. mypy/typeshed/stdlib/keyword.pyi +21 -0
  448. mypy/typeshed/stdlib/lib2to3/__init__.pyi +0 -0
  449. mypy/typeshed/stdlib/lib2to3/btm_matcher.pyi +28 -0
  450. mypy/typeshed/stdlib/lib2to3/fixer_base.pyi +42 -0
  451. mypy/typeshed/stdlib/lib2to3/fixes/__init__.pyi +0 -0
  452. mypy/typeshed/stdlib/lib2to3/fixes/fix_apply.pyi +8 -0
  453. mypy/typeshed/stdlib/lib2to3/fixes/fix_asserts.pyi +10 -0
  454. mypy/typeshed/stdlib/lib2to3/fixes/fix_basestring.pyi +8 -0
  455. mypy/typeshed/stdlib/lib2to3/fixes/fix_buffer.pyi +8 -0
  456. mypy/typeshed/stdlib/lib2to3/fixes/fix_dict.pyi +16 -0
  457. mypy/typeshed/stdlib/lib2to3/fixes/fix_except.pyi +14 -0
  458. mypy/typeshed/stdlib/lib2to3/fixes/fix_exec.pyi +8 -0
  459. mypy/typeshed/stdlib/lib2to3/fixes/fix_execfile.pyi +8 -0
  460. mypy/typeshed/stdlib/lib2to3/fixes/fix_exitfunc.pyi +13 -0
  461. mypy/typeshed/stdlib/lib2to3/fixes/fix_filter.pyi +9 -0
  462. mypy/typeshed/stdlib/lib2to3/fixes/fix_funcattrs.pyi +8 -0
  463. mypy/typeshed/stdlib/lib2to3/fixes/fix_future.pyi +8 -0
  464. mypy/typeshed/stdlib/lib2to3/fixes/fix_getcwdu.pyi +8 -0
  465. mypy/typeshed/stdlib/lib2to3/fixes/fix_has_key.pyi +8 -0
  466. mypy/typeshed/stdlib/lib2to3/fixes/fix_idioms.pyi +15 -0
  467. mypy/typeshed/stdlib/lib2to3/fixes/fix_import.pyi +16 -0
  468. mypy/typeshed/stdlib/lib2to3/fixes/fix_imports.pyi +21 -0
  469. mypy/typeshed/stdlib/lib2to3/fixes/fix_imports2.pyi +6 -0
  470. mypy/typeshed/stdlib/lib2to3/fixes/fix_input.pyi +11 -0
  471. mypy/typeshed/stdlib/lib2to3/fixes/fix_intern.pyi +9 -0
  472. mypy/typeshed/stdlib/lib2to3/fixes/fix_isinstance.pyi +8 -0
  473. mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools.pyi +9 -0
  474. mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools_imports.pyi +7 -0
  475. mypy/typeshed/stdlib/lib2to3/fixes/fix_long.pyi +7 -0
  476. mypy/typeshed/stdlib/lib2to3/fixes/fix_map.pyi +9 -0
  477. mypy/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi +17 -0
  478. mypy/typeshed/stdlib/lib2to3/fixes/fix_methodattrs.pyi +10 -0
  479. mypy/typeshed/stdlib/lib2to3/fixes/fix_ne.pyi +8 -0
  480. mypy/typeshed/stdlib/lib2to3/fixes/fix_next.pyi +19 -0
  481. mypy/typeshed/stdlib/lib2to3/fixes/fix_nonzero.pyi +8 -0
  482. mypy/typeshed/stdlib/lib2to3/fixes/fix_numliterals.pyi +8 -0
  483. mypy/typeshed/stdlib/lib2to3/fixes/fix_operator.pyi +12 -0
  484. mypy/typeshed/stdlib/lib2to3/fixes/fix_paren.pyi +8 -0
  485. mypy/typeshed/stdlib/lib2to3/fixes/fix_print.pyi +12 -0
  486. mypy/typeshed/stdlib/lib2to3/fixes/fix_raise.pyi +8 -0
  487. mypy/typeshed/stdlib/lib2to3/fixes/fix_raw_input.pyi +8 -0
  488. mypy/typeshed/stdlib/lib2to3/fixes/fix_reduce.pyi +8 -0
  489. mypy/typeshed/stdlib/lib2to3/fixes/fix_reload.pyi +9 -0
  490. mypy/typeshed/stdlib/lib2to3/fixes/fix_renames.pyi +17 -0
  491. mypy/typeshed/stdlib/lib2to3/fixes/fix_repr.pyi +8 -0
  492. mypy/typeshed/stdlib/lib2to3/fixes/fix_set_literal.pyi +7 -0
  493. mypy/typeshed/stdlib/lib2to3/fixes/fix_standarderror.pyi +8 -0
  494. mypy/typeshed/stdlib/lib2to3/fixes/fix_sys_exc.pyi +9 -0
  495. mypy/typeshed/stdlib/lib2to3/fixes/fix_throw.pyi +8 -0
  496. mypy/typeshed/stdlib/lib2to3/fixes/fix_tuple_params.pyi +17 -0
  497. mypy/typeshed/stdlib/lib2to3/fixes/fix_types.pyi +8 -0
  498. mypy/typeshed/stdlib/lib2to3/fixes/fix_unicode.pyi +12 -0
  499. mypy/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi +15 -0
  500. mypy/typeshed/stdlib/lib2to3/fixes/fix_ws_comma.pyi +12 -0
  501. mypy/typeshed/stdlib/lib2to3/fixes/fix_xrange.pyi +20 -0
  502. mypy/typeshed/stdlib/lib2to3/fixes/fix_xreadlines.pyi +8 -0
  503. mypy/typeshed/stdlib/lib2to3/fixes/fix_zip.pyi +9 -0
  504. mypy/typeshed/stdlib/lib2to3/main.pyi +42 -0
  505. mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi +9 -0
  506. mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi +27 -0
  507. mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi +24 -0
  508. mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi +7 -0
  509. mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi +30 -0
  510. mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi +50 -0
  511. mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi +67 -0
  512. mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi +96 -0
  513. mypy/typeshed/stdlib/lib2to3/pygram.pyi +114 -0
  514. mypy/typeshed/stdlib/lib2to3/pytree.pyi +117 -0
  515. mypy/typeshed/stdlib/lib2to3/refactor.pyi +82 -0
  516. mypy/typeshed/stdlib/linecache.pyi +23 -0
  517. mypy/typeshed/stdlib/locale.pyi +152 -0
  518. mypy/typeshed/stdlib/logging/__init__.pyi +655 -0
  519. mypy/typeshed/stdlib/logging/config.pyi +134 -0
  520. mypy/typeshed/stdlib/logging/handlers.pyi +275 -0
  521. mypy/typeshed/stdlib/lzma.pyi +197 -0
  522. mypy/typeshed/stdlib/mailbox.pyi +256 -0
  523. mypy/typeshed/stdlib/mailcap.pyi +11 -0
  524. mypy/typeshed/stdlib/marshal.pyi +33 -0
  525. mypy/typeshed/stdlib/math.pyi +125 -0
  526. mypy/typeshed/stdlib/mimetypes.pyi +46 -0
  527. mypy/typeshed/stdlib/mmap.pyi +113 -0
  528. mypy/typeshed/stdlib/modulefinder.pyi +66 -0
  529. mypy/typeshed/stdlib/msilib/__init__.pyi +176 -0
  530. mypy/typeshed/stdlib/msilib/schema.pyi +94 -0
  531. mypy/typeshed/stdlib/msilib/sequence.pyi +13 -0
  532. mypy/typeshed/stdlib/msilib/text.pyi +7 -0
  533. mypy/typeshed/stdlib/msvcrt.pyi +32 -0
  534. mypy/typeshed/stdlib/multiprocessing/__init__.pyi +90 -0
  535. mypy/typeshed/stdlib/multiprocessing/connection.pyi +75 -0
  536. mypy/typeshed/stdlib/multiprocessing/context.pyi +187 -0
  537. mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi +77 -0
  538. mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi +39 -0
  539. mypy/typeshed/stdlib/multiprocessing/forkserver.pyi +31 -0
  540. mypy/typeshed/stdlib/multiprocessing/heap.pyi +36 -0
  541. mypy/typeshed/stdlib/multiprocessing/managers.pyi +212 -0
  542. mypy/typeshed/stdlib/multiprocessing/pool.pyi +103 -0
  543. mypy/typeshed/stdlib/multiprocessing/popen_fork.pyi +23 -0
  544. mypy/typeshed/stdlib/multiprocessing/popen_forkserver.pyi +16 -0
  545. mypy/typeshed/stdlib/multiprocessing/popen_spawn_posix.pyi +20 -0
  546. mypy/typeshed/stdlib/multiprocessing/popen_spawn_win32.pyi +30 -0
  547. mypy/typeshed/stdlib/multiprocessing/process.pyi +39 -0
  548. mypy/typeshed/stdlib/multiprocessing/queues.pyi +41 -0
  549. mypy/typeshed/stdlib/multiprocessing/reduction.pyi +89 -0
  550. mypy/typeshed/stdlib/multiprocessing/resource_sharer.pyi +20 -0
  551. mypy/typeshed/stdlib/multiprocessing/resource_tracker.pyi +18 -0
  552. mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi +40 -0
  553. mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi +101 -0
  554. mypy/typeshed/stdlib/multiprocessing/spawn.pyi +32 -0
  555. mypy/typeshed/stdlib/multiprocessing/synchronize.pyi +54 -0
  556. mypy/typeshed/stdlib/multiprocessing/util.pyi +79 -0
  557. mypy/typeshed/stdlib/netrc.pyi +23 -0
  558. mypy/typeshed/stdlib/nis.pyi +9 -0
  559. mypy/typeshed/stdlib/nntplib.pyi +125 -0
  560. mypy/typeshed/stdlib/nt.pyi +111 -0
  561. mypy/typeshed/stdlib/ntpath.pyi +119 -0
  562. mypy/typeshed/stdlib/nturl2path.pyi +2 -0
  563. mypy/typeshed/stdlib/numbers.pyi +154 -0
  564. mypy/typeshed/stdlib/opcode.pyi +59 -0
  565. mypy/typeshed/stdlib/operator.pyi +110 -0
  566. mypy/typeshed/stdlib/optparse.pyi +252 -0
  567. mypy/typeshed/stdlib/os/__init__.pyi +1139 -0
  568. mypy/typeshed/stdlib/os/path.pyi +8 -0
  569. mypy/typeshed/stdlib/ossaudiodev.pyi +131 -0
  570. mypy/typeshed/stdlib/parser.pyi +24 -0
  571. mypy/typeshed/stdlib/pathlib.pyi +232 -0
  572. mypy/typeshed/stdlib/pdb.pyi +181 -0
  573. mypy/typeshed/stdlib/pickle.pyi +270 -0
  574. mypy/typeshed/stdlib/pickletools.pyi +167 -0
  575. mypy/typeshed/stdlib/pipes.pyi +16 -0
  576. mypy/typeshed/stdlib/pkgutil.pyi +53 -0
  577. mypy/typeshed/stdlib/platform.pyi +42 -0
  578. mypy/typeshed/stdlib/plistlib.pyi +113 -0
  579. mypy/typeshed/stdlib/poplib.pyi +71 -0
  580. mypy/typeshed/stdlib/posix.pyi +359 -0
  581. mypy/typeshed/stdlib/posixpath.pyi +161 -0
  582. mypy/typeshed/stdlib/pprint.pyi +112 -0
  583. mypy/typeshed/stdlib/profile.pyi +31 -0
  584. mypy/typeshed/stdlib/pstats.pyi +78 -0
  585. mypy/typeshed/stdlib/pty.pyi +19 -0
  586. mypy/typeshed/stdlib/pwd.pyi +27 -0
  587. mypy/typeshed/stdlib/py_compile.pyi +34 -0
  588. mypy/typeshed/stdlib/pyclbr.pyi +74 -0
  589. mypy/typeshed/stdlib/pydoc.pyi +261 -0
  590. mypy/typeshed/stdlib/pydoc_data/__init__.pyi +0 -0
  591. mypy/typeshed/stdlib/pydoc_data/topics.pyi +1 -0
  592. mypy/typeshed/stdlib/pyexpat/__init__.pyi +80 -0
  593. mypy/typeshed/stdlib/pyexpat/errors.pyi +49 -0
  594. mypy/typeshed/stdlib/pyexpat/model.pyi +11 -0
  595. mypy/typeshed/stdlib/queue.pyi +58 -0
  596. mypy/typeshed/stdlib/quopri.pyi +11 -0
  597. mypy/typeshed/stdlib/random.pyi +138 -0
  598. mypy/typeshed/stdlib/re.pyi +290 -0
  599. mypy/typeshed/stdlib/readline.pyi +36 -0
  600. mypy/typeshed/stdlib/reprlib.pyi +65 -0
  601. mypy/typeshed/stdlib/resource.pyi +92 -0
  602. mypy/typeshed/stdlib/rlcompleter.pyi +9 -0
  603. mypy/typeshed/stdlib/runpy.pyi +24 -0
  604. mypy/typeshed/stdlib/sched.pyi +42 -0
  605. mypy/typeshed/stdlib/secrets.pyi +15 -0
  606. mypy/typeshed/stdlib/select.pyi +151 -0
  607. mypy/typeshed/stdlib/selectors.pyi +67 -0
  608. mypy/typeshed/stdlib/shelve.pyi +46 -0
  609. mypy/typeshed/stdlib/shlex.pyi +43 -0
  610. mypy/typeshed/stdlib/shutil.pyi +189 -0
  611. mypy/typeshed/stdlib/signal.pyi +189 -0
  612. mypy/typeshed/stdlib/site.pyi +27 -0
  613. mypy/typeshed/stdlib/smtpd.pyi +91 -0
  614. mypy/typeshed/stdlib/smtplib.pyi +204 -0
  615. mypy/typeshed/stdlib/sndhdr.pyi +14 -0
  616. mypy/typeshed/stdlib/socket.pyi +825 -0
  617. mypy/typeshed/stdlib/socketserver.pyi +168 -0
  618. mypy/typeshed/stdlib/spwd.pyi +40 -0
  619. mypy/typeshed/stdlib/sqlite3/__init__.pyi +1 -0
  620. mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +469 -0
  621. mypy/typeshed/stdlib/sre_compile.pyi +11 -0
  622. mypy/typeshed/stdlib/sre_constants.pyi +130 -0
  623. mypy/typeshed/stdlib/sre_parse.pyi +104 -0
  624. mypy/typeshed/stdlib/ssl.pyi +529 -0
  625. mypy/typeshed/stdlib/stat.pyi +1 -0
  626. mypy/typeshed/stdlib/statistics.pyi +132 -0
  627. mypy/typeshed/stdlib/string.pyi +83 -0
  628. mypy/typeshed/stdlib/stringprep.pyi +27 -0
  629. mypy/typeshed/stdlib/struct.pyi +26 -0
  630. mypy/typeshed/stdlib/subprocess.pyi +2614 -0
  631. mypy/typeshed/stdlib/sunau.pyi +86 -0
  632. mypy/typeshed/stdlib/symbol.pyi +93 -0
  633. mypy/typeshed/stdlib/symtable.pyi +58 -0
  634. mypy/typeshed/stdlib/sys/__init__.pyi +373 -0
  635. mypy/typeshed/stdlib/sys/_monitoring.pyi +52 -0
  636. mypy/typeshed/stdlib/sysconfig.pyi +43 -0
  637. mypy/typeshed/stdlib/syslog.pyi +46 -0
  638. mypy/typeshed/stdlib/tabnanny.pyi +16 -0
  639. mypy/typeshed/stdlib/tarfile.pyi +438 -0
  640. mypy/typeshed/stdlib/telnetlib.pyi +122 -0
  641. mypy/typeshed/stdlib/tempfile.pyi +477 -0
  642. mypy/typeshed/stdlib/termios.pyi +267 -0
  643. mypy/typeshed/stdlib/textwrap.pyi +103 -0
  644. mypy/typeshed/stdlib/this.pyi +2 -0
  645. mypy/typeshed/stdlib/threading.pyi +187 -0
  646. mypy/typeshed/stdlib/time.pyi +107 -0
  647. mypy/typeshed/stdlib/timeit.pyi +32 -0
  648. mypy/typeshed/stdlib/tkinter/__init__.pyi +3641 -0
  649. mypy/typeshed/stdlib/tkinter/colorchooser.pyi +20 -0
  650. mypy/typeshed/stdlib/tkinter/commondialog.pyi +14 -0
  651. mypy/typeshed/stdlib/tkinter/constants.pyi +80 -0
  652. mypy/typeshed/stdlib/tkinter/dialog.pyi +16 -0
  653. mypy/typeshed/stdlib/tkinter/dnd.pyi +20 -0
  654. mypy/typeshed/stdlib/tkinter/filedialog.pyi +151 -0
  655. mypy/typeshed/stdlib/tkinter/font.pyi +116 -0
  656. mypy/typeshed/stdlib/tkinter/messagebox.pyi +44 -0
  657. mypy/typeshed/stdlib/tkinter/scrolledtext.pyi +10 -0
  658. mypy/typeshed/stdlib/tkinter/simpledialog.pyi +54 -0
  659. mypy/typeshed/stdlib/tkinter/tix.pyi +299 -0
  660. mypy/typeshed/stdlib/tkinter/ttk.pyi +1191 -0
  661. mypy/typeshed/stdlib/token.pyi +159 -0
  662. mypy/typeshed/stdlib/tokenize.pyi +177 -0
  663. mypy/typeshed/stdlib/tomllib.pyi +10 -0
  664. mypy/typeshed/stdlib/trace.pyi +79 -0
  665. mypy/typeshed/stdlib/traceback.pyi +260 -0
  666. mypy/typeshed/stdlib/tracemalloc.pyi +124 -0
  667. mypy/typeshed/stdlib/tty.pyi +30 -0
  668. mypy/typeshed/stdlib/turtle.pyi +713 -0
  669. mypy/typeshed/stdlib/types.pyi +605 -0
  670. mypy/typeshed/stdlib/typing.pyi +968 -0
  671. mypy/typeshed/stdlib/typing_extensions.pyi +503 -0
  672. mypy/typeshed/stdlib/unicodedata.pyi +71 -0
  673. mypy/typeshed/stdlib/unittest/__init__.pyi +67 -0
  674. mypy/typeshed/stdlib/unittest/_log.pyi +27 -0
  675. mypy/typeshed/stdlib/unittest/async_case.pyi +21 -0
  676. mypy/typeshed/stdlib/unittest/case.pyi +342 -0
  677. mypy/typeshed/stdlib/unittest/loader.pyi +51 -0
  678. mypy/typeshed/stdlib/unittest/main.pyi +69 -0
  679. mypy/typeshed/stdlib/unittest/mock.pyi +430 -0
  680. mypy/typeshed/stdlib/unittest/result.pyi +46 -0
  681. mypy/typeshed/stdlib/unittest/runner.pyi +72 -0
  682. mypy/typeshed/stdlib/unittest/signals.pyi +15 -0
  683. mypy/typeshed/stdlib/unittest/suite.pyi +22 -0
  684. mypy/typeshed/stdlib/unittest/util.pyi +23 -0
  685. mypy/typeshed/stdlib/urllib/__init__.pyi +0 -0
  686. mypy/typeshed/stdlib/urllib/error.pyi +23 -0
  687. mypy/typeshed/stdlib/urllib/parse.pyi +210 -0
  688. mypy/typeshed/stdlib/urllib/request.pyi +399 -0
  689. mypy/typeshed/stdlib/urllib/response.pyi +43 -0
  690. mypy/typeshed/stdlib/urllib/robotparser.pyi +20 -0
  691. mypy/typeshed/stdlib/uu.pyi +13 -0
  692. mypy/typeshed/stdlib/uuid.pyi +100 -0
  693. mypy/typeshed/stdlib/venv/__init__.pyi +79 -0
  694. mypy/typeshed/stdlib/warnings.pyi +112 -0
  695. mypy/typeshed/stdlib/wave.pyi +85 -0
  696. mypy/typeshed/stdlib/weakref.pyi +150 -0
  697. mypy/typeshed/stdlib/webbrowser.pyi +74 -0
  698. mypy/typeshed/stdlib/winreg.pyi +103 -0
  699. mypy/typeshed/stdlib/winsound.pyi +28 -0
  700. mypy/typeshed/stdlib/wsgiref/__init__.pyi +0 -0
  701. mypy/typeshed/stdlib/wsgiref/handlers.pyi +91 -0
  702. mypy/typeshed/stdlib/wsgiref/headers.pyi +26 -0
  703. mypy/typeshed/stdlib/wsgiref/simple_server.pyi +37 -0
  704. mypy/typeshed/stdlib/wsgiref/types.pyi +32 -0
  705. mypy/typeshed/stdlib/wsgiref/util.pyi +24 -0
  706. mypy/typeshed/stdlib/wsgiref/validate.pyi +50 -0
  707. mypy/typeshed/stdlib/xdrlib.pyi +57 -0
  708. mypy/typeshed/stdlib/xml/__init__.pyi +1 -0
  709. mypy/typeshed/stdlib/xml/dom/NodeFilter.pyi +19 -0
  710. mypy/typeshed/stdlib/xml/dom/__init__.pyi +69 -0
  711. mypy/typeshed/stdlib/xml/dom/domreg.pyi +8 -0
  712. mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi +100 -0
  713. mypy/typeshed/stdlib/xml/dom/minicompat.pyi +22 -0
  714. mypy/typeshed/stdlib/xml/dom/minidom.pyi +404 -0
  715. mypy/typeshed/stdlib/xml/dom/pulldom.pyi +94 -0
  716. mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi +108 -0
  717. mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi +28 -0
  718. mypy/typeshed/stdlib/xml/etree/ElementPath.pyi +34 -0
  719. mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +321 -0
  720. mypy/typeshed/stdlib/xml/etree/__init__.pyi +0 -0
  721. mypy/typeshed/stdlib/xml/etree/cElementTree.pyi +1 -0
  722. mypy/typeshed/stdlib/xml/parsers/__init__.pyi +1 -0
  723. mypy/typeshed/stdlib/xml/parsers/expat/__init__.pyi +1 -0
  724. mypy/typeshed/stdlib/xml/parsers/expat/errors.pyi +1 -0
  725. mypy/typeshed/stdlib/xml/parsers/expat/model.pyi +1 -0
  726. mypy/typeshed/stdlib/xml/sax/__init__.pyi +25 -0
  727. mypy/typeshed/stdlib/xml/sax/_exceptions.pyi +19 -0
  728. mypy/typeshed/stdlib/xml/sax/handler.pyi +55 -0
  729. mypy/typeshed/stdlib/xml/sax/saxutils.pyi +60 -0
  730. mypy/typeshed/stdlib/xml/sax/xmlreader.pyi +87 -0
  731. mypy/typeshed/stdlib/xmlrpc/__init__.pyi +0 -0
  732. mypy/typeshed/stdlib/xmlrpc/client.pyi +296 -0
  733. mypy/typeshed/stdlib/xmlrpc/server.pyi +143 -0
  734. mypy/typeshed/stdlib/xxlimited.pyi +22 -0
  735. mypy/typeshed/stdlib/zipapp.pyi +20 -0
  736. mypy/typeshed/stdlib/zipfile/__init__.pyi +306 -0
  737. mypy/typeshed/stdlib/zipfile/_path.pyi +95 -0
  738. mypy/typeshed/stdlib/zipimport.pyi +32 -0
  739. mypy/typeshed/stdlib/zlib.pyi +56 -0
  740. mypy/typeshed/stdlib/zoneinfo/__init__.pyi +38 -0
  741. mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi +218 -0
  742. mypy/typestate.py +323 -0
  743. mypy/typetraverser.py +142 -0
  744. mypy/typevars.py +93 -0
  745. mypy/typevartuples.py +32 -0
  746. mypy/util.py +869 -0
  747. mypy/version.py +1 -0
  748. mypy/visitor.py +621 -0
  749. mypy/xml/mypy-html.css +104 -0
  750. mypy/xml/mypy-html.xslt +81 -0
  751. mypy/xml/mypy-txt.xslt +100 -0
  752. mypy/xml/mypy.xsd +50 -0
  753. mypy_dev-1.9.0.dev0.dist-info/LICENSE +229 -0
  754. mypy_dev-1.9.0.dev0.dist-info/METADATA +39 -0
  755. mypy_dev-1.9.0.dev0.dist-info/RECORD +1018 -0
  756. mypy_dev-1.9.0.dev0.dist-info/WHEEL +5 -0
  757. mypy_dev-1.9.0.dev0.dist-info/entry_points.txt +6 -0
  758. mypy_dev-1.9.0.dev0.dist-info/top_level.txt +2 -0
  759. mypyc/README.md +133 -0
  760. mypyc/__init__.py +0 -0
  761. mypyc/__main__.py +57 -0
  762. mypyc/analysis/__init__.py +0 -0
  763. mypyc/analysis/attrdefined.py +436 -0
  764. mypyc/analysis/blockfreq.py +32 -0
  765. mypyc/analysis/dataflow.py +624 -0
  766. mypyc/analysis/ircheck.py +429 -0
  767. mypyc/analysis/selfleaks.py +207 -0
  768. mypyc/build.py +616 -0
  769. mypyc/codegen/__init__.py +0 -0
  770. mypyc/codegen/cstring.py +54 -0
  771. mypyc/codegen/emit.py +1193 -0
  772. mypyc/codegen/emitclass.py +1060 -0
  773. mypyc/codegen/emitfunc.py +846 -0
  774. mypyc/codegen/emitmodule.py +1131 -0
  775. mypyc/codegen/emitwrapper.py +979 -0
  776. mypyc/codegen/literals.py +302 -0
  777. mypyc/common.py +136 -0
  778. mypyc/crash.py +31 -0
  779. mypyc/doc/Makefile +20 -0
  780. mypyc/doc/bool_operations.rst +27 -0
  781. mypyc/doc/compilation_units.rst +20 -0
  782. mypyc/doc/conf.py +59 -0
  783. mypyc/doc/cpython-timings.md +25 -0
  784. mypyc/doc/dev-intro.md +548 -0
  785. mypyc/doc/dict_operations.rst +59 -0
  786. mypyc/doc/differences_from_python.rst +332 -0
  787. mypyc/doc/float_operations.rst +50 -0
  788. mypyc/doc/future.md +42 -0
  789. mypyc/doc/getting_started.rst +240 -0
  790. mypyc/doc/index.rst +61 -0
  791. mypyc/doc/int_operations.rst +162 -0
  792. mypyc/doc/introduction.rst +150 -0
  793. mypyc/doc/list_operations.rst +65 -0
  794. mypyc/doc/make.bat +35 -0
  795. mypyc/doc/native_classes.rst +206 -0
  796. mypyc/doc/native_operations.rst +55 -0
  797. mypyc/doc/performance_tips_and_tricks.rst +244 -0
  798. mypyc/doc/set_operations.rst +47 -0
  799. mypyc/doc/str_operations.rst +35 -0
  800. mypyc/doc/tuple_operations.rst +33 -0
  801. mypyc/doc/using_type_annotations.rst +398 -0
  802. mypyc/errors.py +29 -0
  803. mypyc/external/googletest/LICENSE +28 -0
  804. mypyc/external/googletest/README.md +280 -0
  805. mypyc/external/googletest/include/gtest/gtest-death-test.h +294 -0
  806. mypyc/external/googletest/include/gtest/gtest-message.h +250 -0
  807. mypyc/external/googletest/include/gtest/gtest-param-test.h +1444 -0
  808. mypyc/external/googletest/include/gtest/gtest-param-test.h.pump +510 -0
  809. mypyc/external/googletest/include/gtest/gtest-printers.h +993 -0
  810. mypyc/external/googletest/include/gtest/gtest-spi.h +232 -0
  811. mypyc/external/googletest/include/gtest/gtest-test-part.h +179 -0
  812. mypyc/external/googletest/include/gtest/gtest-typed-test.h +263 -0
  813. mypyc/external/googletest/include/gtest/gtest.h +2236 -0
  814. mypyc/external/googletest/include/gtest/gtest_pred_impl.h +358 -0
  815. mypyc/external/googletest/include/gtest/gtest_prod.h +58 -0
  816. mypyc/external/googletest/include/gtest/internal/custom/gtest-port.h +69 -0
  817. mypyc/external/googletest/include/gtest/internal/custom/gtest-printers.h +42 -0
  818. mypyc/external/googletest/include/gtest/internal/custom/gtest.h +41 -0
  819. mypyc/external/googletest/include/gtest/internal/gtest-death-test-internal.h +319 -0
  820. mypyc/external/googletest/include/gtest/internal/gtest-filepath.h +206 -0
  821. mypyc/external/googletest/include/gtest/internal/gtest-internal.h +1238 -0
  822. mypyc/external/googletest/include/gtest/internal/gtest-linked_ptr.h +243 -0
  823. mypyc/external/googletest/include/gtest/internal/gtest-param-util-generated.h +5146 -0
  824. mypyc/external/googletest/include/gtest/internal/gtest-param-util-generated.h.pump +286 -0
  825. mypyc/external/googletest/include/gtest/internal/gtest-param-util.h +731 -0
  826. mypyc/external/googletest/include/gtest/internal/gtest-port-arch.h +93 -0
  827. mypyc/external/googletest/include/gtest/internal/gtest-port.h +2560 -0
  828. mypyc/external/googletest/include/gtest/internal/gtest-string.h +167 -0
  829. mypyc/external/googletest/include/gtest/internal/gtest-tuple.h +1020 -0
  830. mypyc/external/googletest/include/gtest/internal/gtest-tuple.h.pump +347 -0
  831. mypyc/external/googletest/include/gtest/internal/gtest-type-util.h +3331 -0
  832. mypyc/external/googletest/include/gtest/internal/gtest-type-util.h.pump +297 -0
  833. mypyc/external/googletest/make/Makefile +61 -0
  834. mypyc/external/googletest/src/gtest-all.cc +48 -0
  835. mypyc/external/googletest/src/gtest-death-test.cc +1342 -0
  836. mypyc/external/googletest/src/gtest-filepath.cc +387 -0
  837. mypyc/external/googletest/src/gtest-internal-inl.h +1183 -0
  838. mypyc/external/googletest/src/gtest-port.cc +1259 -0
  839. mypyc/external/googletest/src/gtest-printers.cc +373 -0
  840. mypyc/external/googletest/src/gtest-test-part.cc +110 -0
  841. mypyc/external/googletest/src/gtest-typed-test.cc +118 -0
  842. mypyc/external/googletest/src/gtest.cc +5388 -0
  843. mypyc/external/googletest/src/gtest_main.cc +38 -0
  844. mypyc/ir/__init__.py +0 -0
  845. mypyc/ir/class_ir.py +499 -0
  846. mypyc/ir/func_ir.py +370 -0
  847. mypyc/ir/module_ir.py +88 -0
  848. mypyc/ir/ops.py +1642 -0
  849. mypyc/ir/pprint.py +496 -0
  850. mypyc/ir/rtypes.py +1038 -0
  851. mypyc/irbuild/__init__.py +0 -0
  852. mypyc/irbuild/ast_helpers.py +120 -0
  853. mypyc/irbuild/builder.py +1398 -0
  854. mypyc/irbuild/callable_class.py +173 -0
  855. mypyc/irbuild/classdef.py +850 -0
  856. mypyc/irbuild/constant_fold.py +95 -0
  857. mypyc/irbuild/context.py +186 -0
  858. mypyc/irbuild/env_class.py +223 -0
  859. mypyc/irbuild/expression.py +1067 -0
  860. mypyc/irbuild/for_helpers.py +1046 -0
  861. mypyc/irbuild/format_str_tokenizer.py +250 -0
  862. mypyc/irbuild/function.py +1089 -0
  863. mypyc/irbuild/generator.py +346 -0
  864. mypyc/irbuild/ll_builder.py +2407 -0
  865. mypyc/irbuild/main.py +153 -0
  866. mypyc/irbuild/mapper.py +221 -0
  867. mypyc/irbuild/match.py +355 -0
  868. mypyc/irbuild/nonlocalcontrol.py +197 -0
  869. mypyc/irbuild/prebuildvisitor.py +203 -0
  870. mypyc/irbuild/prepare.py +609 -0
  871. mypyc/irbuild/specialize.py +822 -0
  872. mypyc/irbuild/statement.py +1017 -0
  873. mypyc/irbuild/targets.py +57 -0
  874. mypyc/irbuild/util.py +189 -0
  875. mypyc/irbuild/visitor.py +401 -0
  876. mypyc/irbuild/vtable.py +82 -0
  877. mypyc/lib-rt/CPy.h +643 -0
  878. mypyc/lib-rt/bytes_ops.c +143 -0
  879. mypyc/lib-rt/dict_ops.c +446 -0
  880. mypyc/lib-rt/exc_ops.c +259 -0
  881. mypyc/lib-rt/float_ops.c +192 -0
  882. mypyc/lib-rt/generic_ops.c +64 -0
  883. mypyc/lib-rt/getargs.c +450 -0
  884. mypyc/lib-rt/getargsfast.c +569 -0
  885. mypyc/lib-rt/init.c +13 -0
  886. mypyc/lib-rt/int_ops.c +803 -0
  887. mypyc/lib-rt/list_ops.c +335 -0
  888. mypyc/lib-rt/misc_ops.c +942 -0
  889. mypyc/lib-rt/module_shim.tmpl +18 -0
  890. mypyc/lib-rt/mypyc_util.h +118 -0
  891. mypyc/lib-rt/pythoncapi_compat.h +497 -0
  892. mypyc/lib-rt/pythonsupport.h +548 -0
  893. mypyc/lib-rt/set_ops.c +17 -0
  894. mypyc/lib-rt/setup.py +70 -0
  895. mypyc/lib-rt/str_ops.c +241 -0
  896. mypyc/lib-rt/test_capi.cc +585 -0
  897. mypyc/lib-rt/tuple_ops.c +61 -0
  898. mypyc/namegen.py +115 -0
  899. mypyc/options.py +32 -0
  900. mypyc/primitives/__init__.py +0 -0
  901. mypyc/primitives/bytes_ops.py +101 -0
  902. mypyc/primitives/dict_ops.py +325 -0
  903. mypyc/primitives/exc_ops.py +101 -0
  904. mypyc/primitives/float_ops.py +168 -0
  905. mypyc/primitives/generic_ops.py +384 -0
  906. mypyc/primitives/int_ops.py +304 -0
  907. mypyc/primitives/list_ops.py +300 -0
  908. mypyc/primitives/misc_ops.py +241 -0
  909. mypyc/primitives/registry.py +323 -0
  910. mypyc/primitives/set_ops.py +121 -0
  911. mypyc/primitives/str_ops.py +229 -0
  912. mypyc/primitives/tuple_ops.py +83 -0
  913. mypyc/rt_subtype.py +77 -0
  914. mypyc/sametype.py +83 -0
  915. mypyc/subtype.py +88 -0
  916. mypyc/test/__init__.py +0 -0
  917. mypyc/test/config.py +13 -0
  918. mypyc/test/test_alwaysdefined.py +46 -0
  919. mypyc/test/test_analysis.py +77 -0
  920. mypyc/test/test_cheader.py +45 -0
  921. mypyc/test/test_commandline.py +82 -0
  922. mypyc/test/test_emit.py +69 -0
  923. mypyc/test/test_emitclass.py +35 -0
  924. mypyc/test/test_emitfunc.py +926 -0
  925. mypyc/test/test_emitwrapper.py +60 -0
  926. mypyc/test/test_exceptions.py +56 -0
  927. mypyc/test/test_external.py +49 -0
  928. mypyc/test/test_irbuild.py +87 -0
  929. mypyc/test/test_ircheck.py +199 -0
  930. mypyc/test/test_literals.py +90 -0
  931. mypyc/test/test_namegen.py +48 -0
  932. mypyc/test/test_pprint.py +42 -0
  933. mypyc/test/test_rarray.py +48 -0
  934. mypyc/test/test_refcount.py +59 -0
  935. mypyc/test/test_run.py +426 -0
  936. mypyc/test/test_serialization.py +108 -0
  937. mypyc/test/test_struct.py +112 -0
  938. mypyc/test/test_tuplename.py +33 -0
  939. mypyc/test/test_typeops.py +97 -0
  940. mypyc/test/testutil.py +283 -0
  941. mypyc/test-data/alwaysdefined.test +732 -0
  942. mypyc/test-data/analysis.test +603 -0
  943. mypyc/test-data/commandline.test +245 -0
  944. mypyc/test-data/driver/driver.py +48 -0
  945. mypyc/test-data/exceptions-freq.test +125 -0
  946. mypyc/test-data/exceptions.test +713 -0
  947. mypyc/test-data/fixtures/ir.py +373 -0
  948. mypyc/test-data/fixtures/testutil.py +103 -0
  949. mypyc/test-data/fixtures/typing-full.pyi +169 -0
  950. mypyc/test-data/irbuild-any.test +238 -0
  951. mypyc/test-data/irbuild-basic.test +3690 -0
  952. mypyc/test-data/irbuild-bool.test +463 -0
  953. mypyc/test-data/irbuild-bytes.test +184 -0
  954. mypyc/test-data/irbuild-classes.test +1303 -0
  955. mypyc/test-data/irbuild-constant-fold.test +480 -0
  956. mypyc/test-data/irbuild-dict.test +585 -0
  957. mypyc/test-data/irbuild-dunders.test +223 -0
  958. mypyc/test-data/irbuild-float.test +497 -0
  959. mypyc/test-data/irbuild-generics.test +151 -0
  960. mypyc/test-data/irbuild-glue-methods.test +437 -0
  961. mypyc/test-data/irbuild-i16.test +526 -0
  962. mypyc/test-data/irbuild-i32.test +598 -0
  963. mypyc/test-data/irbuild-i64.test +2164 -0
  964. mypyc/test-data/irbuild-int.test +235 -0
  965. mypyc/test-data/irbuild-isinstance.test +109 -0
  966. mypyc/test-data/irbuild-lists.test +547 -0
  967. mypyc/test-data/irbuild-match.test +1708 -0
  968. mypyc/test-data/irbuild-math.test +64 -0
  969. mypyc/test-data/irbuild-nested.test +807 -0
  970. mypyc/test-data/irbuild-optional.test +536 -0
  971. mypyc/test-data/irbuild-set.test +838 -0
  972. mypyc/test-data/irbuild-singledispatch.test +257 -0
  973. mypyc/test-data/irbuild-statements.test +1149 -0
  974. mypyc/test-data/irbuild-str.test +314 -0
  975. mypyc/test-data/irbuild-strip-asserts.test +12 -0
  976. mypyc/test-data/irbuild-try.test +523 -0
  977. mypyc/test-data/irbuild-tuple.test +462 -0
  978. mypyc/test-data/irbuild-u8.test +543 -0
  979. mypyc/test-data/irbuild-unreachable.test +241 -0
  980. mypyc/test-data/irbuild-vectorcall.test +153 -0
  981. mypyc/test-data/refcount.test +1588 -0
  982. mypyc/test-data/run-async.test +145 -0
  983. mypyc/test-data/run-attrs.test +318 -0
  984. mypyc/test-data/run-bench.test +196 -0
  985. mypyc/test-data/run-bools.test +229 -0
  986. mypyc/test-data/run-bytes.test +302 -0
  987. mypyc/test-data/run-classes.test +2505 -0
  988. mypyc/test-data/run-dicts.test +334 -0
  989. mypyc/test-data/run-dunders.test +945 -0
  990. mypyc/test-data/run-exceptions.test +448 -0
  991. mypyc/test-data/run-floats.test +516 -0
  992. mypyc/test-data/run-functions.test +1310 -0
  993. mypyc/test-data/run-generators.test +681 -0
  994. mypyc/test-data/run-i16.test +338 -0
  995. mypyc/test-data/run-i32.test +336 -0
  996. mypyc/test-data/run-i64.test +1519 -0
  997. mypyc/test-data/run-imports.test +265 -0
  998. mypyc/test-data/run-integers.test +540 -0
  999. mypyc/test-data/run-lists.test +411 -0
  1000. mypyc/test-data/run-loops.test +485 -0
  1001. mypyc/test-data/run-match.test +283 -0
  1002. mypyc/test-data/run-math.test +106 -0
  1003. mypyc/test-data/run-misc.test +1168 -0
  1004. mypyc/test-data/run-multimodule.test +887 -0
  1005. mypyc/test-data/run-mypy-sim.test +138 -0
  1006. mypyc/test-data/run-primitives.test +375 -0
  1007. mypyc/test-data/run-python37.test +159 -0
  1008. mypyc/test-data/run-python38.test +88 -0
  1009. mypyc/test-data/run-sets.test +150 -0
  1010. mypyc/test-data/run-singledispatch.test +698 -0
  1011. mypyc/test-data/run-strings.test +641 -0
  1012. mypyc/test-data/run-traits.test +411 -0
  1013. mypyc/test-data/run-tuples.test +258 -0
  1014. mypyc/test-data/run-u8.test +303 -0
  1015. mypyc/transform/__init__.py +0 -0
  1016. mypyc/transform/exceptions.py +182 -0
  1017. mypyc/transform/refcount.py +294 -0
  1018. mypyc/transform/uninit.py +190 -0
mypy/stubgen.py ADDED
@@ -0,0 +1,1873 @@
1
+ #!/usr/bin/env python3
2
+ """Generator of dynamically typed draft stubs for arbitrary modules.
3
+
4
+ The logic of this script can be split in three steps:
5
+ * parsing options and finding sources:
6
+ - use runtime imports be default (to find also C modules)
7
+ - or use mypy's mechanisms, if importing is prohibited
8
+ * (optionally) semantically analysing the sources using mypy (as a single set)
9
+ * emitting the stubs text:
10
+ - for Python modules: from ASTs using ASTStubGenerator
11
+ - for C modules using runtime introspection and (optionally) Sphinx docs
12
+
13
+ During first and third steps some problematic files can be skipped, but any
14
+ blocking error during second step will cause the whole program to stop.
15
+
16
+ Basic usage:
17
+
18
+ $ stubgen foo.py bar.py some_directory
19
+ => Generate out/foo.pyi, out/bar.pyi, and stubs for some_directory (recursively).
20
+
21
+ $ stubgen -m urllib.parse
22
+ => Generate out/urllib/parse.pyi.
23
+
24
+ $ stubgen -p urllib
25
+ => Generate stubs for whole urllib package (recursively).
26
+
27
+ For C modules, you can get more precise function signatures by parsing .rst (Sphinx)
28
+ documentation for extra information. For this, use the --doc-dir option:
29
+
30
+ $ stubgen --doc-dir <DIR>/Python-3.4.2/Doc/library -m curses
31
+
32
+ Note: The generated stubs should be verified manually.
33
+
34
+ TODO:
35
+ - maybe use .rst docs also for Python modules
36
+ - maybe export more imported names if there is no __all__ (this affects ssl.SSLError, for example)
37
+ - a quick and dirty heuristic would be to turn this on if a module has something like
38
+ 'from x import y as _y'
39
+ - we don't seem to always detect properties ('closed' in 'io', for example)
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import argparse
45
+ import keyword
46
+ import os
47
+ import os.path
48
+ import sys
49
+ import traceback
50
+ from typing import Final, Iterable
51
+
52
+ import mypy.build
53
+ import mypy.mixedtraverser
54
+ import mypy.parse
55
+ import mypy.traverser
56
+ import mypy.util
57
+ from mypy.build import build
58
+ from mypy.errors import CompileError, Errors
59
+ from mypy.find_sources import InvalidSourceList, create_source_list
60
+ from mypy.modulefinder import (
61
+ BuildSource,
62
+ FindModuleCache,
63
+ ModuleNotFoundReason,
64
+ SearchPaths,
65
+ default_lib_path,
66
+ )
67
+ from mypy.moduleinspect import ModuleInspect, is_pyc_only
68
+ from mypy.nodes import (
69
+ ARG_NAMED,
70
+ ARG_POS,
71
+ ARG_STAR,
72
+ ARG_STAR2,
73
+ IS_ABSTRACT,
74
+ NOT_ABSTRACT,
75
+ AssignmentStmt,
76
+ Block,
77
+ BytesExpr,
78
+ CallExpr,
79
+ ClassDef,
80
+ ComparisonExpr,
81
+ ComplexExpr,
82
+ Decorator,
83
+ DictExpr,
84
+ EllipsisExpr,
85
+ Expression,
86
+ ExpressionStmt,
87
+ FloatExpr,
88
+ FuncBase,
89
+ FuncDef,
90
+ IfStmt,
91
+ Import,
92
+ ImportAll,
93
+ ImportFrom,
94
+ IndexExpr,
95
+ IntExpr,
96
+ ListExpr,
97
+ MemberExpr,
98
+ MypyFile,
99
+ NameExpr,
100
+ OpExpr,
101
+ OverloadedFuncDef,
102
+ SetExpr,
103
+ StarExpr,
104
+ Statement,
105
+ StrExpr,
106
+ TempNode,
107
+ TupleExpr,
108
+ TypeInfo,
109
+ UnaryExpr,
110
+ Var,
111
+ )
112
+ from mypy.options import Options as MypyOptions
113
+ from mypy.stubdoc import ArgSig, FunctionSig
114
+ from mypy.stubgenc import InspectionStubGenerator, generate_stub_for_c_module
115
+ from mypy.stubutil import (
116
+ BaseStubGenerator,
117
+ CantImport,
118
+ ClassInfo,
119
+ FunctionContext,
120
+ common_dir_prefix,
121
+ fail_missing,
122
+ find_module_path_and_all_py3,
123
+ generate_guarded,
124
+ infer_method_arg_types,
125
+ infer_method_ret_type,
126
+ remove_misplaced_type_comments,
127
+ report_missing,
128
+ walk_packages,
129
+ )
130
+ from mypy.traverser import (
131
+ all_yield_expressions,
132
+ has_return_statement,
133
+ has_yield_expression,
134
+ has_yield_from_expression,
135
+ )
136
+ from mypy.types import (
137
+ OVERLOAD_NAMES,
138
+ TPDICT_NAMES,
139
+ TYPED_NAMEDTUPLE_NAMES,
140
+ AnyType,
141
+ CallableType,
142
+ Instance,
143
+ TupleType,
144
+ Type,
145
+ UnboundType,
146
+ get_proper_type,
147
+ )
148
+ from mypy.visitor import NodeVisitor
149
+
150
+ # Common ways of naming package containing vendored modules.
151
+ VENDOR_PACKAGES: Final = ["packages", "vendor", "vendored", "_vendor", "_vendored_packages"]
152
+
153
+ # Avoid some file names that are unnecessary or likely to cause trouble (\n for end of path).
154
+ BLACKLIST: Final = [
155
+ "/six.py\n", # Likely vendored six; too dynamic for us to handle
156
+ "/vendored/", # Vendored packages
157
+ "/vendor/", # Vendored packages
158
+ "/_vendor/",
159
+ "/_vendored_packages/",
160
+ ]
161
+
162
+ # These methods are expected to always return a non-trivial value.
163
+ METHODS_WITH_RETURN_VALUE: Final = {
164
+ "__ne__",
165
+ "__eq__",
166
+ "__lt__",
167
+ "__le__",
168
+ "__gt__",
169
+ "__ge__",
170
+ "__hash__",
171
+ "__iter__",
172
+ }
173
+
174
+
175
+ class Options:
176
+ """Represents stubgen options.
177
+
178
+ This class is mutable to simplify testing.
179
+ """
180
+
181
+ def __init__(
182
+ self,
183
+ pyversion: tuple[int, int],
184
+ no_import: bool,
185
+ inspect: bool,
186
+ doc_dir: str,
187
+ search_path: list[str],
188
+ interpreter: str,
189
+ parse_only: bool,
190
+ ignore_errors: bool,
191
+ include_private: bool,
192
+ output_dir: str,
193
+ modules: list[str],
194
+ packages: list[str],
195
+ files: list[str],
196
+ verbose: bool,
197
+ quiet: bool,
198
+ export_less: bool,
199
+ include_docstrings: bool,
200
+ ) -> None:
201
+ # See parse_options for descriptions of the flags.
202
+ self.pyversion = pyversion
203
+ self.no_import = no_import
204
+ self.inspect = inspect
205
+ self.doc_dir = doc_dir
206
+ self.search_path = search_path
207
+ self.interpreter = interpreter
208
+ self.decointerpreter = interpreter
209
+ self.parse_only = parse_only
210
+ self.ignore_errors = ignore_errors
211
+ self.include_private = include_private
212
+ self.output_dir = output_dir
213
+ self.modules = modules
214
+ self.packages = packages
215
+ self.files = files
216
+ self.verbose = verbose
217
+ self.quiet = quiet
218
+ self.export_less = export_less
219
+ self.include_docstrings = include_docstrings
220
+
221
+
222
+ class StubSource:
223
+ """A single source for stub: can be a Python or C module.
224
+
225
+ A simple extension of BuildSource that also carries the AST and
226
+ the value of __all__ detected at runtime.
227
+ """
228
+
229
+ def __init__(
230
+ self, module: str, path: str | None = None, runtime_all: list[str] | None = None
231
+ ) -> None:
232
+ self.source = BuildSource(path, module, None)
233
+ self.runtime_all = runtime_all
234
+ self.ast: MypyFile | None = None
235
+
236
+ def __repr__(self) -> str:
237
+ return f"StubSource({self.source})"
238
+
239
+ @property
240
+ def module(self) -> str:
241
+ return self.source.module
242
+
243
+ @property
244
+ def path(self) -> str | None:
245
+ return self.source.path
246
+
247
+
248
+ # What was generated previously in the stub file. We keep track of these to generate
249
+ # nicely formatted output (add empty line between non-empty classes, for example).
250
+ EMPTY: Final = "EMPTY"
251
+ FUNC: Final = "FUNC"
252
+ CLASS: Final = "CLASS"
253
+ EMPTY_CLASS: Final = "EMPTY_CLASS"
254
+ VAR: Final = "VAR"
255
+ NOT_IN_ALL: Final = "NOT_IN_ALL"
256
+
257
+ # Indicates that we failed to generate a reasonable output
258
+ # for a given node. These should be manually replaced by a user.
259
+
260
+ ERROR_MARKER: Final = "<ERROR>"
261
+
262
+
263
+ class AliasPrinter(NodeVisitor[str]):
264
+ """Visitor used to collect type aliases _and_ type variable definitions.
265
+
266
+ Visit r.h.s of the definition to get the string representation of type alias.
267
+ """
268
+
269
+ def __init__(self, stubgen: ASTStubGenerator) -> None:
270
+ self.stubgen = stubgen
271
+ super().__init__()
272
+
273
+ def visit_call_expr(self, node: CallExpr) -> str:
274
+ # Call expressions are not usually types, but we also treat `X = TypeVar(...)` as a
275
+ # type alias that has to be preserved (even if TypeVar is not the same as an alias)
276
+ callee = node.callee.accept(self)
277
+ args = []
278
+ for name, arg, kind in zip(node.arg_names, node.args, node.arg_kinds):
279
+ if kind == ARG_POS:
280
+ args.append(arg.accept(self))
281
+ elif kind == ARG_STAR:
282
+ args.append("*" + arg.accept(self))
283
+ elif kind == ARG_STAR2:
284
+ args.append("**" + arg.accept(self))
285
+ elif kind == ARG_NAMED:
286
+ args.append(f"{name}={arg.accept(self)}")
287
+ else:
288
+ raise ValueError(f"Unknown argument kind {kind} in call")
289
+ return f"{callee}({', '.join(args)})"
290
+
291
+ def visit_name_expr(self, node: NameExpr) -> str:
292
+ self.stubgen.import_tracker.require_name(node.name)
293
+ return node.name
294
+
295
+ def visit_member_expr(self, o: MemberExpr) -> str:
296
+ node: Expression = o
297
+ trailer = ""
298
+ while isinstance(node, MemberExpr):
299
+ trailer = "." + node.name + trailer
300
+ node = node.expr
301
+ if not isinstance(node, NameExpr):
302
+ return ERROR_MARKER
303
+ self.stubgen.import_tracker.require_name(node.name)
304
+ return node.name + trailer
305
+
306
+ def visit_str_expr(self, node: StrExpr) -> str:
307
+ return repr(node.value)
308
+
309
+ def visit_index_expr(self, node: IndexExpr) -> str:
310
+ base_fullname = self.stubgen.get_fullname(node.base)
311
+ if base_fullname == "typing.Union":
312
+ if isinstance(node.index, TupleExpr):
313
+ return " | ".join([item.accept(self) for item in node.index.items])
314
+ return node.index.accept(self)
315
+ if base_fullname == "typing.Optional":
316
+ return f"{node.index.accept(self)} | None"
317
+ base = node.base.accept(self)
318
+ index = node.index.accept(self)
319
+ if len(index) > 2 and index.startswith("(") and index.endswith(")"):
320
+ index = index[1:-1]
321
+ return f"{base}[{index}]"
322
+
323
+ def visit_tuple_expr(self, node: TupleExpr) -> str:
324
+ return f"({', '.join(n.accept(self) for n in node.items)})"
325
+
326
+ def visit_list_expr(self, node: ListExpr) -> str:
327
+ return f"[{', '.join(n.accept(self) for n in node.items)}]"
328
+
329
+ def visit_dict_expr(self, o: DictExpr) -> str:
330
+ dict_items = []
331
+ for key, value in o.items:
332
+ # This is currently only used for TypedDict where all keys are strings.
333
+ assert isinstance(key, StrExpr)
334
+ dict_items.append(f"{key.accept(self)}: {value.accept(self)}")
335
+ return f"{{{', '.join(dict_items)}}}"
336
+
337
+ def visit_ellipsis(self, node: EllipsisExpr) -> str:
338
+ return "..."
339
+
340
+ def visit_op_expr(self, o: OpExpr) -> str:
341
+ return f"{o.left.accept(self)} {o.op} {o.right.accept(self)}"
342
+
343
+ def visit_star_expr(self, o: StarExpr) -> str:
344
+ return f"*{o.expr.accept(self)}"
345
+
346
+
347
+ def find_defined_names(file: MypyFile) -> set[str]:
348
+ finder = DefinitionFinder()
349
+ file.accept(finder)
350
+ return finder.names
351
+
352
+
353
+ class DefinitionFinder(mypy.traverser.TraverserVisitor):
354
+ """Find names of things defined at the top level of a module."""
355
+
356
+ # TODO: Assignment statements etc.
357
+
358
+ def __init__(self) -> None:
359
+ # Short names of things defined at the top level.
360
+ self.names: set[str] = set()
361
+
362
+ def visit_class_def(self, o: ClassDef) -> None:
363
+ # Don't recurse into classes, as we only keep track of top-level definitions.
364
+ self.names.add(o.name)
365
+
366
+ def visit_func_def(self, o: FuncDef) -> None:
367
+ # Don't recurse, as we only keep track of top-level definitions.
368
+ self.names.add(o.name)
369
+
370
+
371
+ def find_referenced_names(file: MypyFile) -> set[str]:
372
+ finder = ReferenceFinder()
373
+ file.accept(finder)
374
+ return finder.refs
375
+
376
+
377
+ def is_none_expr(expr: Expression) -> bool:
378
+ return isinstance(expr, NameExpr) and expr.name == "None"
379
+
380
+
381
+ class ReferenceFinder(mypy.mixedtraverser.MixedTraverserVisitor):
382
+ """Find all name references (both local and global)."""
383
+
384
+ # TODO: Filter out local variable and class attribute references
385
+
386
+ def __init__(self) -> None:
387
+ # Short names of things defined at the top level.
388
+ self.refs: set[str] = set()
389
+
390
+ def visit_block(self, block: Block) -> None:
391
+ if not block.is_unreachable:
392
+ super().visit_block(block)
393
+
394
+ def visit_name_expr(self, e: NameExpr) -> None:
395
+ self.refs.add(e.name)
396
+
397
+ def visit_instance(self, t: Instance) -> None:
398
+ self.add_ref(t.type.name)
399
+ super().visit_instance(t)
400
+
401
+ def visit_unbound_type(self, t: UnboundType) -> None:
402
+ if t.name:
403
+ self.add_ref(t.name)
404
+
405
+ def visit_tuple_type(self, t: TupleType) -> None:
406
+ # Ignore fallback
407
+ for item in t.items:
408
+ item.accept(self)
409
+
410
+ def visit_callable_type(self, t: CallableType) -> None:
411
+ # Ignore fallback
412
+ for arg in t.arg_types:
413
+ arg.accept(self)
414
+ t.ret_type.accept(self)
415
+
416
+ def add_ref(self, fullname: str) -> None:
417
+ self.refs.add(fullname)
418
+ while "." in fullname:
419
+ fullname = fullname.rsplit(".", 1)[0]
420
+ self.refs.add(fullname)
421
+
422
+
423
+ class ASTStubGenerator(BaseStubGenerator, mypy.traverser.TraverserVisitor):
424
+ """Generate stub text from a mypy AST."""
425
+
426
+ def __init__(
427
+ self,
428
+ _all_: list[str] | None = None,
429
+ include_private: bool = False,
430
+ analyzed: bool = False,
431
+ export_less: bool = False,
432
+ include_docstrings: bool = False,
433
+ ) -> None:
434
+ super().__init__(_all_, include_private, export_less, include_docstrings)
435
+ self._decorators: list[str] = []
436
+ # Stack of defined variables (per scope).
437
+ self._vars: list[list[str]] = [[]]
438
+ # What was generated previously in the stub file.
439
+ self._state = EMPTY
440
+ self._current_class: ClassDef | None = None
441
+ # Was the tree semantically analysed before?
442
+ self.analyzed = analyzed
443
+ # Short names of methods defined in the body of the current class
444
+ self.method_names: set[str] = set()
445
+ self.processing_dataclass = False
446
+
447
+ def visit_mypy_file(self, o: MypyFile) -> None:
448
+ self.module_name = o.fullname # Current module being processed
449
+ self.path = o.path
450
+ self.set_defined_names(find_defined_names(o))
451
+ self.referenced_names = find_referenced_names(o)
452
+ super().visit_mypy_file(o)
453
+ self.check_undefined_names()
454
+
455
+ def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None:
456
+ """@property with setters and getters, @overload chain and some others."""
457
+ overload_chain = False
458
+ for item in o.items:
459
+ if not isinstance(item, Decorator):
460
+ continue
461
+ if self.is_private_name(item.func.name, item.func.fullname):
462
+ continue
463
+
464
+ self.process_decorator(item)
465
+ if not overload_chain:
466
+ self.visit_func_def(item.func)
467
+ if item.func.is_overload:
468
+ overload_chain = True
469
+ elif item.func.is_overload:
470
+ self.visit_func_def(item.func)
471
+ else:
472
+ # skip the overload implementation and clear the decorator we just processed
473
+ self.clear_decorators()
474
+
475
+ def get_default_function_sig(self, func_def: FuncDef, ctx: FunctionContext) -> FunctionSig:
476
+ args = self._get_func_args(func_def, ctx)
477
+ retname = self._get_func_return(func_def, ctx)
478
+ return FunctionSig(func_def.name, args, retname)
479
+
480
+ def _get_func_args(self, o: FuncDef, ctx: FunctionContext) -> list[ArgSig]:
481
+ args: list[ArgSig] = []
482
+
483
+ for i, arg_ in enumerate(o.arguments):
484
+ var = arg_.variable
485
+ kind = arg_.kind
486
+ name = var.name
487
+ annotated_type = (
488
+ o.unanalyzed_type.arg_types[i]
489
+ if isinstance(o.unanalyzed_type, CallableType)
490
+ else None
491
+ )
492
+ # I think the name check is incorrect: there are libraries which
493
+ # name their 0th argument other than self/cls
494
+ is_self_arg = i == 0 and name == "self"
495
+ is_cls_arg = i == 0 and name == "cls"
496
+ typename: str | None = None
497
+ if annotated_type and not is_self_arg and not is_cls_arg:
498
+ # Luckily, an argument explicitly annotated with "Any" has
499
+ # type "UnboundType" and will not match.
500
+ if not isinstance(get_proper_type(annotated_type), AnyType):
501
+ typename = self.print_annotation(annotated_type)
502
+
503
+ if kind.is_named() and not any(arg.name.startswith("*") for arg in args):
504
+ args.append(ArgSig("*"))
505
+
506
+ default = "..."
507
+ if arg_.initializer:
508
+ if not typename:
509
+ typename = self.get_str_type_of_node(arg_.initializer, True, False)
510
+ potential_default, valid = self.get_str_default_of_node(arg_.initializer)
511
+ if valid and len(potential_default) <= 200:
512
+ default = potential_default
513
+ elif kind == ARG_STAR:
514
+ name = f"*{name}"
515
+ elif kind == ARG_STAR2:
516
+ name = f"**{name}"
517
+
518
+ args.append(
519
+ ArgSig(name, typename, default=bool(arg_.initializer), default_value=default)
520
+ )
521
+
522
+ if ctx.class_info is not None and all(
523
+ arg.type is None and arg.default is False for arg in args
524
+ ):
525
+ new_args = infer_method_arg_types(
526
+ ctx.name, ctx.class_info.self_var, [arg.name for arg in args]
527
+ )
528
+ if new_args is not None:
529
+ args = new_args
530
+
531
+ is_dataclass_generated = (
532
+ self.analyzed and self.processing_dataclass and o.info.names[o.name].plugin_generated
533
+ )
534
+ if o.name == "__init__" and is_dataclass_generated and "**" in [a.name for a in args]:
535
+ # The dataclass plugin generates invalid nameless "*" and "**" arguments
536
+ new_name = "".join(a.name.strip("*") for a in args)
537
+ for arg in args:
538
+ if arg.name == "*":
539
+ arg.name = f"*{new_name}_" # this name is guaranteed to be unique
540
+ elif arg.name == "**":
541
+ arg.name = f"**{new_name}__" # same here
542
+ return args
543
+
544
+ def _get_func_return(self, o: FuncDef, ctx: FunctionContext) -> str | None:
545
+ if o.name != "__init__" and isinstance(o.unanalyzed_type, CallableType):
546
+ if isinstance(get_proper_type(o.unanalyzed_type.ret_type), AnyType):
547
+ # Luckily, a return type explicitly annotated with "Any" has
548
+ # type "UnboundType" and will enter the else branch.
549
+ return None # implicit Any
550
+ else:
551
+ return self.print_annotation(o.unanalyzed_type.ret_type)
552
+ if o.abstract_status == IS_ABSTRACT or o.name in METHODS_WITH_RETURN_VALUE:
553
+ # Always assume abstract methods return Any unless explicitly annotated. Also
554
+ # some dunder methods should not have a None return type.
555
+ return None # implicit Any
556
+ retname = infer_method_ret_type(o.name)
557
+ if retname is not None:
558
+ return retname
559
+ if has_yield_expression(o) or has_yield_from_expression(o):
560
+ generator_name = self.add_name("collections.abc.Generator")
561
+ yield_name = "None"
562
+ send_name = "None"
563
+ return_name = "None"
564
+ if has_yield_from_expression(o):
565
+ yield_name = send_name = self.add_name("_typeshed.Incomplete")
566
+ else:
567
+ for expr, in_assignment in all_yield_expressions(o):
568
+ if expr.expr is not None and not is_none_expr(expr.expr):
569
+ yield_name = self.add_name("_typeshed.Incomplete")
570
+ if in_assignment:
571
+ send_name = self.add_name("_typeshed.Incomplete")
572
+ if has_return_statement(o):
573
+ return_name = self.add_name("_typeshed.Incomplete")
574
+ return f"{generator_name}[{yield_name}, {send_name}, {return_name}]"
575
+ if not has_return_statement(o) and o.abstract_status == NOT_ABSTRACT:
576
+ return "None"
577
+ return None
578
+
579
+ def _get_func_docstring(self, node: FuncDef) -> str | None:
580
+ if not node.body.body:
581
+ return None
582
+ expr = node.body.body[0]
583
+ if isinstance(expr, ExpressionStmt) and isinstance(expr.expr, StrExpr):
584
+ return expr.expr.value
585
+ return None
586
+
587
+ def visit_func_def(self, o: FuncDef) -> None:
588
+ is_dataclass_generated = (
589
+ self.analyzed and self.processing_dataclass and o.info.names[o.name].plugin_generated
590
+ )
591
+ if is_dataclass_generated and o.name != "__init__":
592
+ # Skip methods generated by the @dataclass decorator (except for __init__)
593
+ return
594
+ if (
595
+ self.is_private_name(o.name, o.fullname)
596
+ or self.is_not_in_all(o.name)
597
+ or (self.is_recorded_name(o.name) and not o.is_overload)
598
+ ):
599
+ self.clear_decorators()
600
+ return
601
+ if self.is_top_level() and self._state not in (EMPTY, FUNC):
602
+ self.add("\n")
603
+ if not self.is_top_level():
604
+ self_inits = find_self_initializers(o)
605
+ for init, value in self_inits:
606
+ if init in self.method_names:
607
+ # Can't have both an attribute and a method/property with the same name.
608
+ continue
609
+ init_code = self.get_init(init, value)
610
+ if init_code:
611
+ self.add(init_code)
612
+
613
+ if self._current_class is not None:
614
+ if len(o.arguments):
615
+ self_var = o.arguments[0].variable.name
616
+ else:
617
+ self_var = "self"
618
+ class_info = ClassInfo(self._current_class.name, self_var)
619
+ else:
620
+ class_info = None
621
+
622
+ ctx = FunctionContext(
623
+ module_name=self.module_name,
624
+ name=o.name,
625
+ docstring=self._get_func_docstring(o),
626
+ is_abstract=o.abstract_status != NOT_ABSTRACT,
627
+ class_info=class_info,
628
+ )
629
+
630
+ self.record_name(o.name)
631
+
632
+ default_sig = self.get_default_function_sig(o, ctx)
633
+ sigs = self.get_signatures(default_sig, self.sig_generators, ctx)
634
+
635
+ for output in self.format_func_def(
636
+ sigs, is_coroutine=o.is_coroutine, decorators=self._decorators, docstring=ctx.docstring
637
+ ):
638
+ self.add(output + "\n")
639
+
640
+ self.clear_decorators()
641
+ self._state = FUNC
642
+
643
+ def visit_decorator(self, o: Decorator) -> None:
644
+ if self.is_private_name(o.func.name, o.func.fullname):
645
+ return
646
+ self.process_decorator(o)
647
+ self.visit_func_def(o.func)
648
+
649
+ def process_decorator(self, o: Decorator) -> None:
650
+ """Process a series of decorators.
651
+
652
+ Only preserve certain special decorators such as @abstractmethod.
653
+ """
654
+ o.func.is_overload = False
655
+ for decorator in o.original_decorators:
656
+ if not isinstance(decorator, (NameExpr, MemberExpr)):
657
+ continue
658
+ qualname = get_qualified_name(decorator)
659
+ fullname = self.get_fullname(decorator)
660
+ if fullname in (
661
+ "builtins.property",
662
+ "builtins.staticmethod",
663
+ "builtins.classmethod",
664
+ "functools.cached_property",
665
+ ):
666
+ self.add_decorator(qualname, require_name=True)
667
+ elif fullname in (
668
+ "asyncio.coroutine",
669
+ "asyncio.coroutines.coroutine",
670
+ "types.coroutine",
671
+ ):
672
+ o.func.is_awaitable_coroutine = True
673
+ self.add_decorator(qualname, require_name=True)
674
+ elif fullname == "abc.abstractmethod":
675
+ self.add_decorator(qualname, require_name=True)
676
+ o.func.abstract_status = IS_ABSTRACT
677
+ elif fullname in (
678
+ "abc.abstractproperty",
679
+ "abc.abstractstaticmethod",
680
+ "abc.abstractclassmethod",
681
+ ):
682
+ abc_module = qualname.rpartition(".")[0]
683
+ if not abc_module:
684
+ self.import_tracker.add_import("abc")
685
+ builtin_decorator_replacement = fullname[len("abc.abstract") :]
686
+ self.add_decorator(builtin_decorator_replacement, require_name=False)
687
+ self.add_decorator(f"{abc_module or 'abc'}.abstractmethod", require_name=True)
688
+ o.func.abstract_status = IS_ABSTRACT
689
+ elif fullname in OVERLOAD_NAMES:
690
+ self.add_decorator(qualname, require_name=True)
691
+ o.func.is_overload = True
692
+ elif qualname.endswith((".setter", ".deleter")):
693
+ self.add_decorator(qualname, require_name=False)
694
+
695
+ def get_fullname(self, expr: Expression) -> str:
696
+ """Return the expression's full name."""
697
+ if (
698
+ self.analyzed
699
+ and isinstance(expr, (NameExpr, MemberExpr))
700
+ and expr.fullname
701
+ and not (isinstance(expr.node, Var) and expr.node.is_suppressed_import)
702
+ ):
703
+ return expr.fullname
704
+ name = get_qualified_name(expr)
705
+ return self.resolve_name(name)
706
+
707
+ def visit_class_def(self, o: ClassDef) -> None:
708
+ self._current_class = o
709
+ self.method_names = find_method_names(o.defs.body)
710
+ sep: int | None = None
711
+ if self.is_top_level() and self._state != EMPTY:
712
+ sep = len(self._output)
713
+ self.add("\n")
714
+ decorators = self.get_class_decorators(o)
715
+ for d in decorators:
716
+ self.add(f"{self._indent}@{d}\n")
717
+ self.record_name(o.name)
718
+ base_types = self.get_base_types(o)
719
+ if base_types:
720
+ for base in base_types:
721
+ self.import_tracker.require_name(base)
722
+ if isinstance(o.metaclass, (NameExpr, MemberExpr)):
723
+ meta = o.metaclass.accept(AliasPrinter(self))
724
+ base_types.append("metaclass=" + meta)
725
+ elif self.analyzed and o.info.is_abstract and not o.info.is_protocol:
726
+ base_types.append("metaclass=abc.ABCMeta")
727
+ self.import_tracker.add_import("abc")
728
+ self.import_tracker.require_name("abc")
729
+ bases = f"({', '.join(base_types)})" if base_types else ""
730
+ self.add(f"{self._indent}class {o.name}{bases}:\n")
731
+ self.indent()
732
+ if self._include_docstrings and o.docstring:
733
+ docstring = mypy.util.quote_docstring(o.docstring)
734
+ self.add(f"{self._indent}{docstring}\n")
735
+ n = len(self._output)
736
+ self._vars.append([])
737
+ super().visit_class_def(o)
738
+ self.dedent()
739
+ self._vars.pop()
740
+ self._vars[-1].append(o.name)
741
+ if len(self._output) == n:
742
+ if self._state == EMPTY_CLASS and sep is not None:
743
+ self._output[sep] = ""
744
+ if not (self._include_docstrings and o.docstring):
745
+ self._output[-1] = self._output[-1][:-1] + " ...\n"
746
+ self._state = EMPTY_CLASS
747
+ else:
748
+ self._state = CLASS
749
+ self.method_names = set()
750
+ self.processing_dataclass = False
751
+ self._current_class = None
752
+
753
+ def get_base_types(self, cdef: ClassDef) -> list[str]:
754
+ """Get list of base classes for a class."""
755
+ base_types: list[str] = []
756
+ p = AliasPrinter(self)
757
+ for base in cdef.base_type_exprs + cdef.removed_base_type_exprs:
758
+ if isinstance(base, (NameExpr, MemberExpr)):
759
+ if self.get_fullname(base) != "builtins.object":
760
+ base_types.append(get_qualified_name(base))
761
+ elif isinstance(base, IndexExpr):
762
+ base_types.append(base.accept(p))
763
+ elif isinstance(base, CallExpr):
764
+ # namedtuple(typename, fields), NamedTuple(typename, fields) calls can
765
+ # be used as a base class. The first argument is a string literal that
766
+ # is usually the same as the class name.
767
+ #
768
+ # Note:
769
+ # A call-based named tuple as a base class cannot be safely converted to
770
+ # a class-based NamedTuple definition because class attributes defined
771
+ # in the body of the class inheriting from the named tuple call are not
772
+ # namedtuple fields at runtime.
773
+ if self.is_namedtuple(base):
774
+ nt_fields = self._get_namedtuple_fields(base)
775
+ assert isinstance(base.args[0], StrExpr)
776
+ typename = base.args[0].value
777
+ if nt_fields is None:
778
+ # Invalid namedtuple() call, cannot determine fields
779
+ base_types.append(self.add_name("_typeshed.Incomplete"))
780
+ continue
781
+ fields_str = ", ".join(f"({f!r}, {t})" for f, t in nt_fields)
782
+ namedtuple_name = self.add_name("typing.NamedTuple")
783
+ base_types.append(f"{namedtuple_name}({typename!r}, [{fields_str}])")
784
+ elif self.is_typed_namedtuple(base):
785
+ base_types.append(base.accept(p))
786
+ else:
787
+ # At this point, we don't know what the base class is, so we
788
+ # just use Incomplete as the base class.
789
+ base_types.append(self.add_name("_typeshed.Incomplete"))
790
+ for name, value in cdef.keywords.items():
791
+ if name == "metaclass":
792
+ continue # handled separately
793
+ base_types.append(f"{name}={value.accept(p)}")
794
+ return base_types
795
+
796
+ def get_class_decorators(self, cdef: ClassDef) -> list[str]:
797
+ decorators: list[str] = []
798
+ p = AliasPrinter(self)
799
+ for d in cdef.decorators:
800
+ if self.is_dataclass(d):
801
+ decorators.append(d.accept(p))
802
+ self.import_tracker.require_name(get_qualified_name(d))
803
+ self.processing_dataclass = True
804
+ return decorators
805
+
806
+ def is_dataclass(self, expr: Expression) -> bool:
807
+ if isinstance(expr, CallExpr):
808
+ expr = expr.callee
809
+ return self.get_fullname(expr) == "dataclasses.dataclass"
810
+
811
+ def visit_block(self, o: Block) -> None:
812
+ # Unreachable statements may be partially uninitialized and that may
813
+ # cause trouble.
814
+ if not o.is_unreachable:
815
+ super().visit_block(o)
816
+
817
+ def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
818
+ foundl = []
819
+
820
+ for lvalue in o.lvalues:
821
+ if isinstance(lvalue, NameExpr) and isinstance(o.rvalue, CallExpr):
822
+ if self.is_namedtuple(o.rvalue) or self.is_typed_namedtuple(o.rvalue):
823
+ self.process_namedtuple(lvalue, o.rvalue)
824
+ foundl.append(False) # state is updated in process_namedtuple
825
+ continue
826
+ if self.is_typeddict(o.rvalue):
827
+ self.process_typeddict(lvalue, o.rvalue)
828
+ foundl.append(False) # state is updated in process_typeddict
829
+ continue
830
+ if (
831
+ isinstance(lvalue, NameExpr)
832
+ and not self.is_private_name(lvalue.name)
833
+ # it is never an alias with explicit annotation
834
+ and not o.unanalyzed_type
835
+ and self.is_alias_expression(o.rvalue)
836
+ ):
837
+ self.process_typealias(lvalue, o.rvalue)
838
+ continue
839
+ if isinstance(lvalue, (TupleExpr, ListExpr)):
840
+ items = lvalue.items
841
+ if isinstance(o.unanalyzed_type, TupleType): # type: ignore[misc]
842
+ annotations: Iterable[Type | None] = o.unanalyzed_type.items
843
+ else:
844
+ annotations = [None] * len(items)
845
+ else:
846
+ items = [lvalue]
847
+ annotations = [o.unanalyzed_type]
848
+ sep = False
849
+ found = False
850
+ for item, annotation in zip(items, annotations):
851
+ if isinstance(item, NameExpr):
852
+ init = self.get_init(item.name, o.rvalue, annotation)
853
+ if init:
854
+ found = True
855
+ if not sep and self.is_top_level() and self._state not in (EMPTY, VAR):
856
+ init = "\n" + init
857
+ sep = True
858
+ self.add(init)
859
+ self.record_name(item.name)
860
+ foundl.append(found)
861
+
862
+ if all(foundl):
863
+ self._state = VAR
864
+
865
+ def is_namedtuple(self, expr: CallExpr) -> bool:
866
+ return self.get_fullname(expr.callee) == "collections.namedtuple"
867
+
868
+ def is_typed_namedtuple(self, expr: CallExpr) -> bool:
869
+ return self.get_fullname(expr.callee) in TYPED_NAMEDTUPLE_NAMES
870
+
871
+ def _get_namedtuple_fields(self, call: CallExpr) -> list[tuple[str, str]] | None:
872
+ if self.is_namedtuple(call):
873
+ fields_arg = call.args[1]
874
+ if isinstance(fields_arg, StrExpr):
875
+ field_names = fields_arg.value.replace(",", " ").split()
876
+ elif isinstance(fields_arg, (ListExpr, TupleExpr)):
877
+ field_names = []
878
+ for field in fields_arg.items:
879
+ if not isinstance(field, StrExpr):
880
+ return None
881
+ field_names.append(field.value)
882
+ else:
883
+ return None # Invalid namedtuple fields type
884
+ if field_names:
885
+ incomplete = self.add_name("_typeshed.Incomplete")
886
+ return [(field_name, incomplete) for field_name in field_names]
887
+ else:
888
+ return []
889
+
890
+ elif self.is_typed_namedtuple(call):
891
+ fields_arg = call.args[1]
892
+ if not isinstance(fields_arg, (ListExpr, TupleExpr)):
893
+ return None
894
+ fields: list[tuple[str, str]] = []
895
+ p = AliasPrinter(self)
896
+ for field in fields_arg.items:
897
+ if not (isinstance(field, TupleExpr) and len(field.items) == 2):
898
+ return None
899
+ field_name, field_type = field.items
900
+ if not isinstance(field_name, StrExpr):
901
+ return None
902
+ fields.append((field_name.value, field_type.accept(p)))
903
+ return fields
904
+ else:
905
+ return None # Not a named tuple call
906
+
907
+ def process_namedtuple(self, lvalue: NameExpr, rvalue: CallExpr) -> None:
908
+ if self._state == CLASS:
909
+ self.add("\n")
910
+
911
+ if not isinstance(rvalue.args[0], StrExpr):
912
+ self.annotate_as_incomplete(lvalue)
913
+ return
914
+
915
+ fields = self._get_namedtuple_fields(rvalue)
916
+ if fields is None:
917
+ self.annotate_as_incomplete(lvalue)
918
+ return
919
+ bases = self.add_name("typing.NamedTuple")
920
+ # TODO: Add support for generic NamedTuples. Requires `Generic` as base class.
921
+ class_def = f"{self._indent}class {lvalue.name}({bases}):"
922
+ if len(fields) == 0:
923
+ self.add(f"{class_def} ...\n")
924
+ self._state = EMPTY_CLASS
925
+ else:
926
+ if self._state not in (EMPTY, CLASS):
927
+ self.add("\n")
928
+ self.add(f"{class_def}\n")
929
+ for f_name, f_type in fields:
930
+ self.add(f"{self._indent} {f_name}: {f_type}\n")
931
+ self._state = CLASS
932
+
933
+ def is_typeddict(self, expr: CallExpr) -> bool:
934
+ return self.get_fullname(expr.callee) in TPDICT_NAMES
935
+
936
+ def process_typeddict(self, lvalue: NameExpr, rvalue: CallExpr) -> None:
937
+ if self._state == CLASS:
938
+ self.add("\n")
939
+
940
+ if not isinstance(rvalue.args[0], StrExpr):
941
+ self.annotate_as_incomplete(lvalue)
942
+ return
943
+
944
+ items: list[tuple[str, Expression]] = []
945
+ total: Expression | None = None
946
+ if len(rvalue.args) > 1 and rvalue.arg_kinds[1] == ARG_POS:
947
+ if not isinstance(rvalue.args[1], DictExpr):
948
+ self.annotate_as_incomplete(lvalue)
949
+ return
950
+ for attr_name, attr_type in rvalue.args[1].items:
951
+ if not isinstance(attr_name, StrExpr):
952
+ self.annotate_as_incomplete(lvalue)
953
+ return
954
+ items.append((attr_name.value, attr_type))
955
+ if len(rvalue.args) > 2:
956
+ if rvalue.arg_kinds[2] != ARG_NAMED or rvalue.arg_names[2] != "total":
957
+ self.annotate_as_incomplete(lvalue)
958
+ return
959
+ total = rvalue.args[2]
960
+ else:
961
+ for arg_name, arg in zip(rvalue.arg_names[1:], rvalue.args[1:]):
962
+ if not isinstance(arg_name, str):
963
+ self.annotate_as_incomplete(lvalue)
964
+ return
965
+ if arg_name == "total":
966
+ total = arg
967
+ else:
968
+ items.append((arg_name, arg))
969
+ p = AliasPrinter(self)
970
+ if any(not key.isidentifier() or keyword.iskeyword(key) for key, _ in items):
971
+ # Keep the call syntax if there are non-identifier or reserved keyword keys.
972
+ self.add(f"{self._indent}{lvalue.name} = {rvalue.accept(p)}\n")
973
+ self._state = VAR
974
+ else:
975
+ bases = self.add_name("typing_extensions.TypedDict")
976
+ # TODO: Add support for generic TypedDicts. Requires `Generic` as base class.
977
+ if total is not None:
978
+ bases += f", total={total.accept(p)}"
979
+ class_def = f"{self._indent}class {lvalue.name}({bases}):"
980
+ if len(items) == 0:
981
+ self.add(f"{class_def} ...\n")
982
+ self._state = EMPTY_CLASS
983
+ else:
984
+ if self._state not in (EMPTY, CLASS):
985
+ self.add("\n")
986
+ self.add(f"{class_def}\n")
987
+ for key, key_type in items:
988
+ self.add(f"{self._indent} {key}: {key_type.accept(p)}\n")
989
+ self._state = CLASS
990
+
991
+ def annotate_as_incomplete(self, lvalue: NameExpr) -> None:
992
+ incomplete = self.add_name("_typeshed.Incomplete")
993
+ self.add(f"{self._indent}{lvalue.name}: {incomplete}\n")
994
+ self._state = VAR
995
+
996
+ def is_alias_expression(self, expr: Expression, top_level: bool = True) -> bool:
997
+ """Return True for things that look like target for an alias.
998
+
999
+ Used to know if assignments look like type aliases, function alias,
1000
+ or module alias.
1001
+ """
1002
+ # Assignment of TypeVar(...) and other typevar-likes are passed through
1003
+ if isinstance(expr, CallExpr) and self.get_fullname(expr.callee) in (
1004
+ "typing.TypeVar",
1005
+ "typing_extensions.TypeVar",
1006
+ "typing.ParamSpec",
1007
+ "typing_extensions.ParamSpec",
1008
+ "typing.TypeVarTuple",
1009
+ "typing_extensions.TypeVarTuple",
1010
+ ):
1011
+ return True
1012
+ elif isinstance(expr, EllipsisExpr):
1013
+ return not top_level
1014
+ elif isinstance(expr, NameExpr):
1015
+ if expr.name in ("True", "False"):
1016
+ return False
1017
+ elif expr.name == "None":
1018
+ return not top_level
1019
+ else:
1020
+ return not self.is_private_name(expr.name)
1021
+ elif isinstance(expr, MemberExpr) and self.analyzed:
1022
+ # Also add function and module aliases.
1023
+ return (
1024
+ top_level
1025
+ and isinstance(expr.node, (FuncDef, Decorator, MypyFile))
1026
+ or isinstance(expr.node, TypeInfo)
1027
+ ) and not self.is_private_member(expr.node.fullname)
1028
+ elif (
1029
+ isinstance(expr, IndexExpr)
1030
+ and isinstance(expr.base, NameExpr)
1031
+ and not self.is_private_name(expr.base.name)
1032
+ ):
1033
+ if isinstance(expr.index, TupleExpr):
1034
+ indices = expr.index.items
1035
+ else:
1036
+ indices = [expr.index]
1037
+ if expr.base.name == "Callable" and len(indices) == 2:
1038
+ args, ret = indices
1039
+ if isinstance(args, EllipsisExpr):
1040
+ indices = [ret]
1041
+ elif isinstance(args, ListExpr):
1042
+ indices = args.items + [ret]
1043
+ else:
1044
+ return False
1045
+ return all(self.is_alias_expression(i, top_level=False) for i in indices)
1046
+ else:
1047
+ return False
1048
+
1049
+ def process_typealias(self, lvalue: NameExpr, rvalue: Expression) -> None:
1050
+ p = AliasPrinter(self)
1051
+ self.add(f"{self._indent}{lvalue.name} = {rvalue.accept(p)}\n")
1052
+ self.record_name(lvalue.name)
1053
+ self._vars[-1].append(lvalue.name)
1054
+
1055
+ def visit_if_stmt(self, o: IfStmt) -> None:
1056
+ # Ignore if __name__ == '__main__'.
1057
+ expr = o.expr[0]
1058
+ if (
1059
+ isinstance(expr, ComparisonExpr)
1060
+ and isinstance(expr.operands[0], NameExpr)
1061
+ and isinstance(expr.operands[1], StrExpr)
1062
+ and expr.operands[0].name == "__name__"
1063
+ and "__main__" in expr.operands[1].value
1064
+ ):
1065
+ return
1066
+ super().visit_if_stmt(o)
1067
+
1068
+ def visit_import_all(self, o: ImportAll) -> None:
1069
+ self.add_import_line(f"from {'.' * o.relative}{o.id} import *\n")
1070
+
1071
+ def visit_import_from(self, o: ImportFrom) -> None:
1072
+ exported_names: set[str] = set()
1073
+ import_names = []
1074
+ module, relative = translate_module_name(o.id, o.relative)
1075
+ if self.module_name:
1076
+ full_module, ok = mypy.util.correct_relative_import(
1077
+ self.module_name, relative, module, self.path.endswith(".__init__.py")
1078
+ )
1079
+ if not ok:
1080
+ full_module = module
1081
+ else:
1082
+ full_module = module
1083
+ if module == "__future__":
1084
+ return # Not preserved
1085
+ for name, as_name in o.names:
1086
+ if name == "six":
1087
+ # Vendored six -- translate into plain 'import six'.
1088
+ self.visit_import(Import([("six", None)]))
1089
+ continue
1090
+ if self.should_reexport(name, full_module, as_name is not None):
1091
+ self.import_tracker.reexport(name)
1092
+ as_name = name
1093
+ import_names.append((name, as_name))
1094
+ self.import_tracker.add_import_from("." * relative + module, import_names)
1095
+ self._vars[-1].extend(alias or name for name, alias in import_names)
1096
+ for name, alias in import_names:
1097
+ self.record_name(alias or name)
1098
+
1099
+ if self._all_:
1100
+ # Include "import from"s that import names defined in __all__.
1101
+ names = [
1102
+ name
1103
+ for name, alias in o.names
1104
+ if name in self._all_ and alias is None and name not in self.IGNORED_DUNDERS
1105
+ ]
1106
+ exported_names.update(names)
1107
+
1108
+ def visit_import(self, o: Import) -> None:
1109
+ for id, as_id in o.ids:
1110
+ self.import_tracker.add_import(id, as_id)
1111
+ if as_id is None:
1112
+ target_name = id.split(".")[0]
1113
+ else:
1114
+ target_name = as_id
1115
+ self._vars[-1].append(target_name)
1116
+ self.record_name(target_name)
1117
+
1118
+ def get_init(
1119
+ self, lvalue: str, rvalue: Expression, annotation: Type | None = None
1120
+ ) -> str | None:
1121
+ """Return initializer for a variable.
1122
+
1123
+ Return None if we've generated one already or if the variable is internal.
1124
+ """
1125
+ if lvalue in self._vars[-1]:
1126
+ # We've generated an initializer already for this variable.
1127
+ return None
1128
+ # TODO: Only do this at module top level.
1129
+ if self.is_private_name(lvalue) or self.is_not_in_all(lvalue):
1130
+ return None
1131
+ self._vars[-1].append(lvalue)
1132
+ if annotation is not None:
1133
+ typename = self.print_annotation(annotation)
1134
+ if (
1135
+ isinstance(annotation, UnboundType)
1136
+ and not annotation.args
1137
+ and annotation.name == "Final"
1138
+ and self.import_tracker.module_for.get("Final") in self.TYPING_MODULE_NAMES
1139
+ ):
1140
+ # Final without type argument is invalid in stubs.
1141
+ final_arg = self.get_str_type_of_node(rvalue)
1142
+ typename += f"[{final_arg}]"
1143
+ elif self.processing_dataclass:
1144
+ # attribute without annotation is not a dataclass field, don't add annotation.
1145
+ return f"{self._indent}{lvalue} = ...\n"
1146
+ else:
1147
+ typename = self.get_str_type_of_node(rvalue)
1148
+ initializer = self.get_assign_initializer(rvalue)
1149
+ return f"{self._indent}{lvalue}: {typename}{initializer}\n"
1150
+
1151
+ def get_assign_initializer(self, rvalue: Expression) -> str:
1152
+ """Does this rvalue need some special initializer value?"""
1153
+ if not self._current_class:
1154
+ return ""
1155
+ # Current rules
1156
+ # 1. Return `...` if we are dealing with `NamedTuple` or `dataclass` field and
1157
+ # it has an existing default value
1158
+ if (
1159
+ self._current_class.info
1160
+ and self._current_class.info.is_named_tuple
1161
+ and not isinstance(rvalue, TempNode)
1162
+ ):
1163
+ return " = ..."
1164
+ if self.processing_dataclass and not (isinstance(rvalue, TempNode) and rvalue.no_rhs):
1165
+ return " = ..."
1166
+ # TODO: support other possible cases, where initializer is important
1167
+
1168
+ # By default, no initializer is required:
1169
+ return ""
1170
+
1171
+ def add_decorator(self, name: str, require_name: bool = False) -> None:
1172
+ if require_name:
1173
+ self.import_tracker.require_name(name)
1174
+ self._decorators.append(f"@{name}")
1175
+
1176
+ def clear_decorators(self) -> None:
1177
+ self._decorators.clear()
1178
+
1179
+ def is_private_member(self, fullname: str) -> bool:
1180
+ parts = fullname.split(".")
1181
+ return any(self.is_private_name(part) for part in parts)
1182
+
1183
+ def get_str_type_of_node(
1184
+ self, rvalue: Expression, can_infer_optional: bool = False, can_be_any: bool = True
1185
+ ) -> str:
1186
+ rvalue = self.maybe_unwrap_unary_expr(rvalue)
1187
+
1188
+ if isinstance(rvalue, IntExpr):
1189
+ return "int"
1190
+ if isinstance(rvalue, StrExpr):
1191
+ return "str"
1192
+ if isinstance(rvalue, BytesExpr):
1193
+ return "bytes"
1194
+ if isinstance(rvalue, FloatExpr):
1195
+ return "float"
1196
+ if isinstance(rvalue, ComplexExpr): # 1j
1197
+ return "complex"
1198
+ if isinstance(rvalue, OpExpr) and rvalue.op in ("-", "+"): # -1j + 1
1199
+ if isinstance(self.maybe_unwrap_unary_expr(rvalue.left), ComplexExpr) or isinstance(
1200
+ self.maybe_unwrap_unary_expr(rvalue.right), ComplexExpr
1201
+ ):
1202
+ return "complex"
1203
+ if isinstance(rvalue, NameExpr) and rvalue.name in ("True", "False"):
1204
+ return "bool"
1205
+ if can_infer_optional and isinstance(rvalue, NameExpr) and rvalue.name == "None":
1206
+ return f"{self.add_name('_typeshed.Incomplete')} | None"
1207
+ if can_be_any:
1208
+ return self.add_name("_typeshed.Incomplete")
1209
+ else:
1210
+ return ""
1211
+
1212
+ def maybe_unwrap_unary_expr(self, expr: Expression) -> Expression:
1213
+ """Unwrap (possibly nested) unary expressions.
1214
+
1215
+ But, some unary expressions can change the type of expression.
1216
+ While we want to preserve it. For example, `~True` is `int`.
1217
+ So, we only allow a subset of unary expressions to be unwrapped.
1218
+ """
1219
+ if not isinstance(expr, UnaryExpr):
1220
+ return expr
1221
+
1222
+ # First, try to unwrap `[+-]+ (int|float|complex)` expr:
1223
+ math_ops = ("+", "-")
1224
+ if expr.op in math_ops:
1225
+ while isinstance(expr, UnaryExpr):
1226
+ if expr.op not in math_ops or not isinstance(
1227
+ expr.expr, (IntExpr, FloatExpr, ComplexExpr, UnaryExpr)
1228
+ ):
1229
+ break
1230
+ expr = expr.expr
1231
+ return expr
1232
+
1233
+ # Next, try `not bool` expr:
1234
+ if expr.op == "not":
1235
+ while isinstance(expr, UnaryExpr):
1236
+ if expr.op != "not" or not isinstance(expr.expr, (NameExpr, UnaryExpr)):
1237
+ break
1238
+ if isinstance(expr.expr, NameExpr) and expr.expr.name not in ("True", "False"):
1239
+ break
1240
+ expr = expr.expr
1241
+ return expr
1242
+
1243
+ # This is some other unary expr, we cannot do anything with it (yet?).
1244
+ return expr
1245
+
1246
+ def get_str_default_of_node(self, rvalue: Expression) -> tuple[str, bool]:
1247
+ """Get a string representation of the default value of a node.
1248
+
1249
+ Returns a 2-tuple of the default and whether or not it is valid.
1250
+ """
1251
+ if isinstance(rvalue, NameExpr):
1252
+ if rvalue.name in ("None", "True", "False"):
1253
+ return rvalue.name, True
1254
+ elif isinstance(rvalue, (IntExpr, FloatExpr)):
1255
+ return f"{rvalue.value}", True
1256
+ elif isinstance(rvalue, UnaryExpr):
1257
+ if isinstance(rvalue.expr, (IntExpr, FloatExpr)):
1258
+ return f"{rvalue.op}{rvalue.expr.value}", True
1259
+ elif isinstance(rvalue, StrExpr):
1260
+ return repr(rvalue.value), True
1261
+ elif isinstance(rvalue, BytesExpr):
1262
+ return "b" + repr(rvalue.value).replace("\\\\", "\\"), True
1263
+ elif isinstance(rvalue, TupleExpr):
1264
+ items_defaults = []
1265
+ for e in rvalue.items:
1266
+ e_default, valid = self.get_str_default_of_node(e)
1267
+ if not valid:
1268
+ break
1269
+ items_defaults.append(e_default)
1270
+ else:
1271
+ closing = ",)" if len(items_defaults) == 1 else ")"
1272
+ default = "(" + ", ".join(items_defaults) + closing
1273
+ return default, True
1274
+ elif isinstance(rvalue, ListExpr):
1275
+ items_defaults = []
1276
+ for e in rvalue.items:
1277
+ e_default, valid = self.get_str_default_of_node(e)
1278
+ if not valid:
1279
+ break
1280
+ items_defaults.append(e_default)
1281
+ else:
1282
+ default = "[" + ", ".join(items_defaults) + "]"
1283
+ return default, True
1284
+ elif isinstance(rvalue, SetExpr):
1285
+ items_defaults = []
1286
+ for e in rvalue.items:
1287
+ e_default, valid = self.get_str_default_of_node(e)
1288
+ if not valid:
1289
+ break
1290
+ items_defaults.append(e_default)
1291
+ else:
1292
+ if items_defaults:
1293
+ default = "{" + ", ".join(items_defaults) + "}"
1294
+ return default, True
1295
+ elif isinstance(rvalue, DictExpr):
1296
+ items_defaults = []
1297
+ for k, v in rvalue.items:
1298
+ if k is None:
1299
+ break
1300
+ k_default, k_valid = self.get_str_default_of_node(k)
1301
+ v_default, v_valid = self.get_str_default_of_node(v)
1302
+ if not (k_valid and v_valid):
1303
+ break
1304
+ items_defaults.append(f"{k_default}: {v_default}")
1305
+ else:
1306
+ default = "{" + ", ".join(items_defaults) + "}"
1307
+ return default, True
1308
+ return "...", False
1309
+
1310
+ def should_reexport(self, name: str, full_module: str, name_is_alias: bool) -> bool:
1311
+ is_private = self.is_private_name(name, full_module + "." + name)
1312
+ if (
1313
+ not name_is_alias
1314
+ and name not in self.referenced_names
1315
+ and (not self._all_ or name in self.IGNORED_DUNDERS)
1316
+ and not is_private
1317
+ and full_module not in ("abc", "asyncio") + self.TYPING_MODULE_NAMES
1318
+ ):
1319
+ # An imported name that is never referenced in the module is assumed to be
1320
+ # exported, unless there is an explicit __all__. Note that we need to special
1321
+ # case 'abc' since some references are deleted during semantic analysis.
1322
+ return True
1323
+ return super().should_reexport(name, full_module, name_is_alias)
1324
+
1325
+
1326
+ def find_method_names(defs: list[Statement]) -> set[str]:
1327
+ # TODO: Traverse into nested definitions
1328
+ result = set()
1329
+ for defn in defs:
1330
+ if isinstance(defn, FuncDef):
1331
+ result.add(defn.name)
1332
+ elif isinstance(defn, Decorator):
1333
+ result.add(defn.func.name)
1334
+ elif isinstance(defn, OverloadedFuncDef):
1335
+ for item in defn.items:
1336
+ result.update(find_method_names([item]))
1337
+ return result
1338
+
1339
+
1340
+ class SelfTraverser(mypy.traverser.TraverserVisitor):
1341
+ def __init__(self) -> None:
1342
+ self.results: list[tuple[str, Expression]] = []
1343
+
1344
+ def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
1345
+ lvalue = o.lvalues[0]
1346
+ if (
1347
+ isinstance(lvalue, MemberExpr)
1348
+ and isinstance(lvalue.expr, NameExpr)
1349
+ and lvalue.expr.name == "self"
1350
+ ):
1351
+ self.results.append((lvalue.name, o.rvalue))
1352
+
1353
+
1354
+ def find_self_initializers(fdef: FuncBase) -> list[tuple[str, Expression]]:
1355
+ """Find attribute initializers in a method.
1356
+
1357
+ Return a list of pairs (attribute name, r.h.s. expression).
1358
+ """
1359
+ traverser = SelfTraverser()
1360
+ fdef.accept(traverser)
1361
+ return traverser.results
1362
+
1363
+
1364
+ def get_qualified_name(o: Expression) -> str:
1365
+ if isinstance(o, NameExpr):
1366
+ return o.name
1367
+ elif isinstance(o, MemberExpr):
1368
+ return f"{get_qualified_name(o.expr)}.{o.name}"
1369
+ else:
1370
+ return ERROR_MARKER
1371
+
1372
+
1373
+ def remove_blacklisted_modules(modules: list[StubSource]) -> list[StubSource]:
1374
+ return [
1375
+ module for module in modules if module.path is None or not is_blacklisted_path(module.path)
1376
+ ]
1377
+
1378
+
1379
+ def split_pyc_from_py(modules: list[StubSource]) -> tuple[list[StubSource], list[StubSource]]:
1380
+ py_modules = []
1381
+ pyc_modules = []
1382
+ for mod in modules:
1383
+ if is_pyc_only(mod.path):
1384
+ pyc_modules.append(mod)
1385
+ else:
1386
+ py_modules.append(mod)
1387
+ return pyc_modules, py_modules
1388
+
1389
+
1390
+ def is_blacklisted_path(path: str) -> bool:
1391
+ return any(substr in (normalize_path_separators(path) + "\n") for substr in BLACKLIST)
1392
+
1393
+
1394
+ def normalize_path_separators(path: str) -> str:
1395
+ if sys.platform == "win32":
1396
+ return path.replace("\\", "/")
1397
+ return path
1398
+
1399
+
1400
+ def collect_build_targets(
1401
+ options: Options, mypy_opts: MypyOptions
1402
+ ) -> tuple[list[StubSource], list[StubSource], list[StubSource]]:
1403
+ """Collect files for which we need to generate stubs.
1404
+
1405
+ Return list of py modules, pyc modules, and C modules.
1406
+ """
1407
+ if options.packages or options.modules:
1408
+ if options.no_import:
1409
+ py_modules = find_module_paths_using_search(
1410
+ options.modules, options.packages, options.search_path, options.pyversion
1411
+ )
1412
+ c_modules: list[StubSource] = []
1413
+ else:
1414
+ # Using imports is the default, since we can also find C modules.
1415
+ py_modules, c_modules = find_module_paths_using_imports(
1416
+ options.modules, options.packages, options.verbose, options.quiet
1417
+ )
1418
+ else:
1419
+ # Use mypy native source collection for files and directories.
1420
+ try:
1421
+ source_list = create_source_list(options.files, mypy_opts)
1422
+ except InvalidSourceList as e:
1423
+ raise SystemExit(str(e)) from e
1424
+ py_modules = [StubSource(m.module, m.path) for m in source_list]
1425
+ c_modules = []
1426
+
1427
+ py_modules = remove_blacklisted_modules(py_modules)
1428
+ pyc_mod, py_mod = split_pyc_from_py(py_modules)
1429
+ return py_mod, pyc_mod, c_modules
1430
+
1431
+
1432
+ def find_module_paths_using_imports(
1433
+ modules: list[str], packages: list[str], verbose: bool, quiet: bool
1434
+ ) -> tuple[list[StubSource], list[StubSource]]:
1435
+ """Find path and runtime value of __all__ (if possible) for modules and packages.
1436
+
1437
+ This function uses runtime Python imports to get the information.
1438
+ """
1439
+ with ModuleInspect() as inspect:
1440
+ py_modules: list[StubSource] = []
1441
+ c_modules: list[StubSource] = []
1442
+ found = list(walk_packages(inspect, packages, verbose))
1443
+ modules = modules + found
1444
+ modules = [
1445
+ mod for mod in modules if not is_non_library_module(mod)
1446
+ ] # We don't want to run any tests or scripts
1447
+ for mod in modules:
1448
+ try:
1449
+ result = find_module_path_and_all_py3(inspect, mod, verbose)
1450
+ except CantImport as e:
1451
+ tb = traceback.format_exc()
1452
+ if verbose:
1453
+ sys.stdout.write(tb)
1454
+ if not quiet:
1455
+ report_missing(mod, e.message, tb)
1456
+ continue
1457
+ if not result:
1458
+ c_modules.append(StubSource(mod))
1459
+ else:
1460
+ path, runtime_all = result
1461
+ py_modules.append(StubSource(mod, path, runtime_all))
1462
+ return py_modules, c_modules
1463
+
1464
+
1465
+ def is_non_library_module(module: str) -> bool:
1466
+ """Does module look like a test module or a script?"""
1467
+ if module.endswith(
1468
+ (
1469
+ ".tests",
1470
+ ".test",
1471
+ ".testing",
1472
+ "_tests",
1473
+ "_test_suite",
1474
+ "test_util",
1475
+ "test_utils",
1476
+ "test_base",
1477
+ ".__main__",
1478
+ ".conftest", # Used by pytest
1479
+ ".setup", # Typically an install script
1480
+ )
1481
+ ):
1482
+ return True
1483
+ if module.split(".")[-1].startswith("test_"):
1484
+ return True
1485
+ if (
1486
+ ".tests." in module
1487
+ or ".test." in module
1488
+ or ".testing." in module
1489
+ or ".SelfTest." in module
1490
+ ):
1491
+ return True
1492
+ return False
1493
+
1494
+
1495
+ def translate_module_name(module: str, relative: int) -> tuple[str, int]:
1496
+ for pkg in VENDOR_PACKAGES:
1497
+ for alt in "six.moves", "six":
1498
+ substr = f"{pkg}.{alt}"
1499
+ if module.endswith("." + substr) or (module == substr and relative):
1500
+ return alt, 0
1501
+ if "." + substr + "." in module:
1502
+ return alt + "." + module.partition("." + substr + ".")[2], 0
1503
+ return module, relative
1504
+
1505
+
1506
+ def find_module_paths_using_search(
1507
+ modules: list[str], packages: list[str], search_path: list[str], pyversion: tuple[int, int]
1508
+ ) -> list[StubSource]:
1509
+ """Find sources for modules and packages requested.
1510
+
1511
+ This function just looks for source files at the file system level.
1512
+ This is used if user passes --no-import, and will not find C modules.
1513
+ Exit if some of the modules or packages can't be found.
1514
+ """
1515
+ result: list[StubSource] = []
1516
+ typeshed_path = default_lib_path(mypy.build.default_data_dir(), pyversion, None)
1517
+ search_paths = SearchPaths((".",) + tuple(search_path), (), (), tuple(typeshed_path))
1518
+ cache = FindModuleCache(search_paths, fscache=None, options=None)
1519
+ for module in modules:
1520
+ m_result = cache.find_module(module)
1521
+ if isinstance(m_result, ModuleNotFoundReason):
1522
+ fail_missing(module, m_result)
1523
+ module_path = None
1524
+ else:
1525
+ module_path = m_result
1526
+ result.append(StubSource(module, module_path))
1527
+ for package in packages:
1528
+ p_result = cache.find_modules_recursive(package)
1529
+ if p_result:
1530
+ fail_missing(package, ModuleNotFoundReason.NOT_FOUND)
1531
+ sources = [StubSource(m.module, m.path) for m in p_result]
1532
+ result.extend(sources)
1533
+
1534
+ result = [m for m in result if not is_non_library_module(m.module)]
1535
+
1536
+ return result
1537
+
1538
+
1539
+ def mypy_options(stubgen_options: Options) -> MypyOptions:
1540
+ """Generate mypy options using the flag passed by user."""
1541
+ options = MypyOptions()
1542
+ options.follow_imports = "skip"
1543
+ options.incremental = False
1544
+ options.ignore_errors = True
1545
+ options.semantic_analysis_only = True
1546
+ options.python_version = stubgen_options.pyversion
1547
+ options.show_traceback = True
1548
+ options.transform_source = remove_misplaced_type_comments
1549
+ options.preserve_asts = True
1550
+ options.include_docstrings = stubgen_options.include_docstrings
1551
+
1552
+ # Override cache_dir if provided in the environment
1553
+ environ_cache_dir = os.getenv("MYPY_CACHE_DIR", "")
1554
+ if environ_cache_dir.strip():
1555
+ options.cache_dir = environ_cache_dir
1556
+ options.cache_dir = os.path.expanduser(options.cache_dir)
1557
+
1558
+ return options
1559
+
1560
+
1561
+ def parse_source_file(mod: StubSource, mypy_options: MypyOptions) -> None:
1562
+ """Parse a source file.
1563
+
1564
+ On success, store AST in the corresponding attribute of the stub source.
1565
+ If there are syntax errors, print them and exit.
1566
+ """
1567
+ assert mod.path is not None, "Not found module was not skipped"
1568
+ with open(mod.path, "rb") as f:
1569
+ data = f.read()
1570
+ source = mypy.util.decode_python_encoding(data)
1571
+ errors = Errors(mypy_options)
1572
+ mod.ast = mypy.parse.parse(
1573
+ source, fnam=mod.path, module=mod.module, errors=errors, options=mypy_options
1574
+ )
1575
+ mod.ast._fullname = mod.module
1576
+ if errors.is_blockers():
1577
+ # Syntax error!
1578
+ for m in errors.new_messages():
1579
+ sys.stderr.write(f"{m}\n")
1580
+ sys.exit(1)
1581
+
1582
+
1583
+ def generate_asts_for_modules(
1584
+ py_modules: list[StubSource], parse_only: bool, mypy_options: MypyOptions, verbose: bool
1585
+ ) -> None:
1586
+ """Use mypy to parse (and optionally analyze) source files."""
1587
+ if not py_modules:
1588
+ return # Nothing to do here, but there may be C modules
1589
+ if verbose:
1590
+ print(f"Processing {len(py_modules)} files...")
1591
+ if parse_only:
1592
+ for mod in py_modules:
1593
+ parse_source_file(mod, mypy_options)
1594
+ return
1595
+ # Perform full semantic analysis of the source set.
1596
+ try:
1597
+ res = build([module.source for module in py_modules], mypy_options)
1598
+ except CompileError as e:
1599
+ raise SystemExit(f"Critical error during semantic analysis: {e}") from e
1600
+
1601
+ for mod in py_modules:
1602
+ mod.ast = res.graph[mod.module].tree
1603
+ # Use statically inferred __all__ if there is no runtime one.
1604
+ if mod.runtime_all is None:
1605
+ mod.runtime_all = res.manager.semantic_analyzer.export_map[mod.module]
1606
+
1607
+
1608
+ def generate_stub_for_py_module(
1609
+ mod: StubSource,
1610
+ target: str,
1611
+ *,
1612
+ parse_only: bool = False,
1613
+ inspect: bool = False,
1614
+ include_private: bool = False,
1615
+ export_less: bool = False,
1616
+ include_docstrings: bool = False,
1617
+ doc_dir: str = "",
1618
+ all_modules: list[str],
1619
+ ) -> None:
1620
+ """Use analysed (or just parsed) AST to generate type stub for single file.
1621
+
1622
+ If directory for target doesn't exist it will created. Existing stub
1623
+ will be overwritten.
1624
+ """
1625
+ if inspect:
1626
+ ngen = InspectionStubGenerator(
1627
+ module_name=mod.module,
1628
+ known_modules=all_modules,
1629
+ _all_=mod.runtime_all,
1630
+ doc_dir=doc_dir,
1631
+ include_private=include_private,
1632
+ export_less=export_less,
1633
+ include_docstrings=include_docstrings,
1634
+ )
1635
+ ngen.generate_module()
1636
+ output = ngen.output()
1637
+
1638
+ else:
1639
+ gen = ASTStubGenerator(
1640
+ mod.runtime_all,
1641
+ include_private=include_private,
1642
+ analyzed=not parse_only,
1643
+ export_less=export_less,
1644
+ include_docstrings=include_docstrings,
1645
+ )
1646
+ assert mod.ast is not None, "This function must be used only with analyzed modules"
1647
+ mod.ast.accept(gen)
1648
+ output = gen.output()
1649
+
1650
+ # Write output to file.
1651
+ subdir = os.path.dirname(target)
1652
+ if subdir and not os.path.isdir(subdir):
1653
+ os.makedirs(subdir)
1654
+ with open(target, "w", encoding="utf-8") as file:
1655
+ file.write(output)
1656
+
1657
+
1658
+ def generate_stubs(options: Options) -> None:
1659
+ """Main entry point for the program."""
1660
+ mypy_opts = mypy_options(options)
1661
+ py_modules, pyc_modules, c_modules = collect_build_targets(options, mypy_opts)
1662
+ all_modules = py_modules + pyc_modules + c_modules
1663
+ all_module_names = sorted(m.module for m in all_modules)
1664
+ # Use parsed sources to generate stubs for Python modules.
1665
+ generate_asts_for_modules(py_modules, options.parse_only, mypy_opts, options.verbose)
1666
+ files = []
1667
+ for mod in py_modules + pyc_modules:
1668
+ assert mod.path is not None, "Not found module was not skipped"
1669
+ target = mod.module.replace(".", "/")
1670
+ if os.path.basename(mod.path) in ["__init__.py", "__init__.pyc"]:
1671
+ target += "/__init__.pyi"
1672
+ else:
1673
+ target += ".pyi"
1674
+ target = os.path.join(options.output_dir, target)
1675
+ files.append(target)
1676
+ with generate_guarded(mod.module, target, options.ignore_errors, options.verbose):
1677
+ generate_stub_for_py_module(
1678
+ mod,
1679
+ target,
1680
+ parse_only=options.parse_only,
1681
+ inspect=options.inspect or mod in pyc_modules,
1682
+ include_private=options.include_private,
1683
+ export_less=options.export_less,
1684
+ include_docstrings=options.include_docstrings,
1685
+ doc_dir=options.doc_dir,
1686
+ all_modules=all_module_names,
1687
+ )
1688
+
1689
+ # Separately analyse C modules using different logic.
1690
+ for mod in c_modules:
1691
+ if any(py_mod.module.startswith(mod.module + ".") for py_mod in all_modules):
1692
+ target = mod.module.replace(".", "/") + "/__init__.pyi"
1693
+ else:
1694
+ target = mod.module.replace(".", "/") + ".pyi"
1695
+ target = os.path.join(options.output_dir, target)
1696
+ files.append(target)
1697
+ with generate_guarded(mod.module, target, options.ignore_errors, options.verbose):
1698
+ generate_stub_for_c_module(
1699
+ mod.module,
1700
+ target,
1701
+ known_modules=all_module_names,
1702
+ doc_dir=options.doc_dir,
1703
+ include_private=options.include_private,
1704
+ export_less=options.export_less,
1705
+ include_docstrings=options.include_docstrings,
1706
+ )
1707
+ num_modules = len(all_modules)
1708
+ if not options.quiet and num_modules > 0:
1709
+ print("Processed %d modules" % num_modules)
1710
+ if len(files) == 1:
1711
+ print(f"Generated {files[0]}")
1712
+ else:
1713
+ print(f"Generated files under {common_dir_prefix(files)}" + os.sep)
1714
+
1715
+
1716
+ HEADER = """%(prog)s [-h] [more options, see -h]
1717
+ [-m MODULE] [-p PACKAGE] [files ...]"""
1718
+
1719
+ DESCRIPTION = """
1720
+ Generate draft stubs for modules.
1721
+
1722
+ Stubs are generated in directory ./out, to avoid overriding files with
1723
+ manual changes. This directory is assumed to exist.
1724
+ """
1725
+
1726
+
1727
+ def parse_options(args: list[str]) -> Options:
1728
+ parser = argparse.ArgumentParser(prog="stubgen", usage=HEADER, description=DESCRIPTION)
1729
+
1730
+ parser.add_argument(
1731
+ "--ignore-errors",
1732
+ action="store_true",
1733
+ help="ignore errors when trying to generate stubs for modules",
1734
+ )
1735
+ parser.add_argument(
1736
+ "--no-import",
1737
+ action="store_true",
1738
+ help="don't import the modules, just parse and analyze them "
1739
+ "(doesn't work with C extension modules and might not "
1740
+ "respect __all__)",
1741
+ )
1742
+ parser.add_argument(
1743
+ "--no-analysis",
1744
+ "--parse-only",
1745
+ dest="parse_only",
1746
+ action="store_true",
1747
+ help="don't perform semantic analysis of sources, just parse them "
1748
+ "(only applies to Python modules, might affect quality of stubs. "
1749
+ "Not compatible with --inspect)",
1750
+ )
1751
+ parser.add_argument(
1752
+ "--inspect-mode",
1753
+ dest="inspect",
1754
+ action="store_true",
1755
+ help="import and inspect modules instead of parsing source code."
1756
+ "This is the default behavior for c modules and pyc-only packages, but "
1757
+ "it is also useful for pure python modules with dynamically generated members.",
1758
+ )
1759
+ parser.add_argument(
1760
+ "--include-private",
1761
+ action="store_true",
1762
+ help="generate stubs for objects and members considered private "
1763
+ "(single leading underscore and no trailing underscores)",
1764
+ )
1765
+ parser.add_argument(
1766
+ "--export-less",
1767
+ action="store_true",
1768
+ help="don't implicitly export all names imported from other modules in the same package",
1769
+ )
1770
+ parser.add_argument(
1771
+ "--include-docstrings",
1772
+ action="store_true",
1773
+ help="include existing docstrings with the stubs",
1774
+ )
1775
+ parser.add_argument("-v", "--verbose", action="store_true", help="show more verbose messages")
1776
+ parser.add_argument("-q", "--quiet", action="store_true", help="show fewer messages")
1777
+ parser.add_argument(
1778
+ "--doc-dir",
1779
+ metavar="PATH",
1780
+ default="",
1781
+ help="use .rst documentation in PATH (this may result in "
1782
+ "better stubs in some cases; consider setting this to "
1783
+ "DIR/Python-X.Y.Z/Doc/library)",
1784
+ )
1785
+ parser.add_argument(
1786
+ "--search-path",
1787
+ metavar="PATH",
1788
+ default="",
1789
+ help="specify module search directories, separated by ':' "
1790
+ "(currently only used if --no-import is given)",
1791
+ )
1792
+ parser.add_argument(
1793
+ "-o",
1794
+ "--output",
1795
+ metavar="PATH",
1796
+ dest="output_dir",
1797
+ default="out",
1798
+ help="change the output directory [default: %(default)s]",
1799
+ )
1800
+ parser.add_argument(
1801
+ "-m",
1802
+ "--module",
1803
+ action="append",
1804
+ metavar="MODULE",
1805
+ dest="modules",
1806
+ default=[],
1807
+ help="generate stub for module; can repeat for more modules",
1808
+ )
1809
+ parser.add_argument(
1810
+ "-p",
1811
+ "--package",
1812
+ action="append",
1813
+ metavar="PACKAGE",
1814
+ dest="packages",
1815
+ default=[],
1816
+ help="generate stubs for package recursively; can be repeated",
1817
+ )
1818
+ parser.add_argument(
1819
+ metavar="files",
1820
+ nargs="*",
1821
+ dest="files",
1822
+ help="generate stubs for given files or directories",
1823
+ )
1824
+
1825
+ ns = parser.parse_args(args)
1826
+
1827
+ pyversion = sys.version_info[:2]
1828
+ ns.interpreter = sys.executable
1829
+
1830
+ if ns.modules + ns.packages and ns.files:
1831
+ parser.error("May only specify one of: modules/packages or files.")
1832
+ if ns.quiet and ns.verbose:
1833
+ parser.error("Cannot specify both quiet and verbose messages")
1834
+ if ns.inspect and ns.parse_only:
1835
+ parser.error("Cannot specify both --parse-only/--no-analysis and --inspect-mode")
1836
+
1837
+ # Create the output folder if it doesn't already exist.
1838
+ os.makedirs(ns.output_dir, exist_ok=True)
1839
+
1840
+ return Options(
1841
+ pyversion=pyversion,
1842
+ no_import=ns.no_import,
1843
+ inspect=ns.inspect,
1844
+ doc_dir=ns.doc_dir,
1845
+ search_path=ns.search_path.split(":"),
1846
+ interpreter=ns.interpreter,
1847
+ ignore_errors=ns.ignore_errors,
1848
+ parse_only=ns.parse_only,
1849
+ include_private=ns.include_private,
1850
+ output_dir=ns.output_dir,
1851
+ modules=ns.modules,
1852
+ packages=ns.packages,
1853
+ files=ns.files,
1854
+ verbose=ns.verbose,
1855
+ quiet=ns.quiet,
1856
+ export_less=ns.export_less,
1857
+ include_docstrings=ns.include_docstrings,
1858
+ )
1859
+
1860
+
1861
+ def main(args: list[str] | None = None) -> None:
1862
+ mypy.util.check_python_version("stubgen")
1863
+ # Make sure that the current directory is in sys.path so that
1864
+ # stubgen can be run on packages in the current directory.
1865
+ if not ("" in sys.path or "." in sys.path):
1866
+ sys.path.insert(0, "")
1867
+
1868
+ options = parse_options(sys.argv[1:] if args is None else args)
1869
+ generate_stubs(options)
1870
+
1871
+
1872
+ if __name__ == "__main__":
1873
+ main()