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/messages.py ADDED
@@ -0,0 +1,3171 @@
1
+ """Facilities for generating error messages during type checking.
2
+
3
+ Don't add any non-trivial message construction logic to the type
4
+ checker, as it can compromise clarity and make messages less
5
+ consistent. Add such logic to this module instead. Literal messages, including those
6
+ with format args, should be defined as constants in mypy.message_registry.
7
+
8
+ Historically we tried to avoid all message string literals in the type
9
+ checker but we are moving away from this convention.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import difflib
15
+ import itertools
16
+ import re
17
+ from contextlib import contextmanager
18
+ from textwrap import dedent
19
+ from typing import Any, Callable, Collection, Final, Iterable, Iterator, List, Sequence, cast
20
+
21
+ import mypy.typeops
22
+ from mypy import errorcodes as codes, message_registry
23
+ from mypy.erasetype import erase_type
24
+ from mypy.errorcodes import ErrorCode
25
+ from mypy.errors import ErrorInfo, Errors, ErrorWatcher
26
+ from mypy.nodes import (
27
+ ARG_NAMED,
28
+ ARG_NAMED_OPT,
29
+ ARG_OPT,
30
+ ARG_POS,
31
+ ARG_STAR,
32
+ ARG_STAR2,
33
+ CONTRAVARIANT,
34
+ COVARIANT,
35
+ SYMBOL_FUNCBASE_TYPES,
36
+ ArgKind,
37
+ CallExpr,
38
+ ClassDef,
39
+ Context,
40
+ Expression,
41
+ FuncDef,
42
+ IndexExpr,
43
+ MypyFile,
44
+ NameExpr,
45
+ ReturnStmt,
46
+ StrExpr,
47
+ SymbolNode,
48
+ SymbolTable,
49
+ TypeInfo,
50
+ Var,
51
+ reverse_builtin_aliases,
52
+ )
53
+ from mypy.operators import op_methods, op_methods_to_symbols
54
+ from mypy.options import Options
55
+ from mypy.subtypes import (
56
+ IS_CLASS_OR_STATIC,
57
+ IS_CLASSVAR,
58
+ IS_SETTABLE,
59
+ IS_VAR,
60
+ find_member,
61
+ get_member_flags,
62
+ is_same_type,
63
+ is_subtype,
64
+ )
65
+ from mypy.typeops import separate_union_literals
66
+ from mypy.types import (
67
+ AnyType,
68
+ CallableType,
69
+ DeletedType,
70
+ FunctionLike,
71
+ Instance,
72
+ LiteralType,
73
+ NoneType,
74
+ Overloaded,
75
+ Parameters,
76
+ ParamSpecType,
77
+ PartialType,
78
+ ProperType,
79
+ TupleType,
80
+ Type,
81
+ TypeAliasType,
82
+ TypedDictType,
83
+ TypeOfAny,
84
+ TypeStrVisitor,
85
+ TypeType,
86
+ TypeVarTupleType,
87
+ TypeVarType,
88
+ UnboundType,
89
+ UninhabitedType,
90
+ UnionType,
91
+ UnpackType,
92
+ get_proper_type,
93
+ get_proper_types,
94
+ )
95
+ from mypy.typetraverser import TypeTraverserVisitor
96
+ from mypy.util import plural_s, unmangle
97
+
98
+ TYPES_FOR_UNIMPORTED_HINTS: Final = {
99
+ "typing.Any",
100
+ "typing.Callable",
101
+ "typing.Dict",
102
+ "typing.Iterable",
103
+ "typing.Iterator",
104
+ "typing.List",
105
+ "typing.Optional",
106
+ "typing.Set",
107
+ "typing.Tuple",
108
+ "typing.TypeVar",
109
+ "typing.Union",
110
+ "typing.cast",
111
+ }
112
+
113
+
114
+ ARG_CONSTRUCTOR_NAMES: Final = {
115
+ ARG_POS: "Arg",
116
+ ARG_OPT: "DefaultArg",
117
+ ARG_NAMED: "NamedArg",
118
+ ARG_NAMED_OPT: "DefaultNamedArg",
119
+ ARG_STAR: "VarArg",
120
+ ARG_STAR2: "KwArg",
121
+ }
122
+
123
+
124
+ # Map from the full name of a missing definition to the test fixture (under
125
+ # test-data/unit/fixtures/) that provides the definition. This is used for
126
+ # generating better error messages when running mypy tests only.
127
+ SUGGESTED_TEST_FIXTURES: Final = {
128
+ "builtins.set": "set.pyi",
129
+ "builtins.tuple": "tuple.pyi",
130
+ "builtins.bool": "bool.pyi",
131
+ "builtins.Exception": "exception.pyi",
132
+ "builtins.BaseException": "exception.pyi",
133
+ "builtins.isinstance": "isinstancelist.pyi",
134
+ "builtins.property": "property.pyi",
135
+ "builtins.classmethod": "classmethod.pyi",
136
+ "typing._SpecialForm": "typing-medium.pyi",
137
+ }
138
+
139
+ UNSUPPORTED_NUMBERS_TYPES: Final = {
140
+ "numbers.Number",
141
+ "numbers.Complex",
142
+ "numbers.Real",
143
+ "numbers.Rational",
144
+ "numbers.Integral",
145
+ }
146
+
147
+
148
+ class MessageBuilder:
149
+ """Helper class for reporting type checker error messages with parameters.
150
+
151
+ The methods of this class need to be provided with the context within a
152
+ file; the errors member manages the wider context.
153
+
154
+ IDEA: Support a 'verbose mode' that includes full information about types
155
+ in error messages and that may otherwise produce more detailed error
156
+ messages.
157
+ """
158
+
159
+ # Report errors using this instance. It knows about the current file and
160
+ # import context.
161
+ errors: Errors
162
+
163
+ modules: dict[str, MypyFile]
164
+
165
+ # Hack to deduplicate error messages from union types
166
+ _disable_type_names: list[bool]
167
+
168
+ def __init__(self, errors: Errors, modules: dict[str, MypyFile]) -> None:
169
+ self.errors = errors
170
+ self.options = errors.options
171
+ self.modules = modules
172
+ self._disable_type_names = []
173
+
174
+ #
175
+ # Helpers
176
+ #
177
+
178
+ def filter_errors(
179
+ self,
180
+ *,
181
+ filter_errors: bool | Callable[[str, ErrorInfo], bool] = True,
182
+ save_filtered_errors: bool = False,
183
+ ) -> ErrorWatcher:
184
+ return ErrorWatcher(
185
+ self.errors, filter_errors=filter_errors, save_filtered_errors=save_filtered_errors
186
+ )
187
+
188
+ def add_errors(self, errors: list[ErrorInfo]) -> None:
189
+ """Add errors in messages to this builder."""
190
+ for info in errors:
191
+ self.errors.add_error_info(info)
192
+
193
+ @contextmanager
194
+ def disable_type_names(self) -> Iterator[None]:
195
+ self._disable_type_names.append(True)
196
+ try:
197
+ yield
198
+ finally:
199
+ self._disable_type_names.pop()
200
+
201
+ def are_type_names_disabled(self) -> bool:
202
+ return len(self._disable_type_names) > 0 and self._disable_type_names[-1]
203
+
204
+ def prefer_simple_messages(self) -> bool:
205
+ """Should we generate simple/fast error messages?
206
+
207
+ If errors aren't shown to the user, we don't want to waste cyles producing
208
+ complex error messages.
209
+ """
210
+ return self.errors.prefer_simple_messages()
211
+
212
+ def report(
213
+ self,
214
+ msg: str,
215
+ context: Context | None,
216
+ severity: str,
217
+ *,
218
+ code: ErrorCode | None = None,
219
+ file: str | None = None,
220
+ origin: Context | None = None,
221
+ offset: int = 0,
222
+ allow_dups: bool = False,
223
+ secondary_context: Context | None = None,
224
+ ) -> None:
225
+ """Report an error or note (unless disabled).
226
+
227
+ Note that context controls where error is reported, while origin controls
228
+ where # type: ignore comments have effect.
229
+ """
230
+
231
+ def span_from_context(ctx: Context) -> Iterable[int]:
232
+ """This determines where a type: ignore for a given context has effect.
233
+
234
+ Current logic is a bit tricky, to keep as much backwards compatibility as
235
+ possible. We may reconsider this to always be a single line (or otherwise
236
+ simplify it) when we drop Python 3.7.
237
+
238
+ TODO: address this in follow up PR
239
+ """
240
+ if isinstance(ctx, (ClassDef, FuncDef)):
241
+ return range(ctx.deco_line or ctx.line, ctx.line + 1)
242
+ elif not isinstance(ctx, Expression):
243
+ return [ctx.line]
244
+ else:
245
+ return range(ctx.line, (ctx.end_line or ctx.line) + 1)
246
+
247
+ origin_span: Iterable[int] | None
248
+ if origin is not None:
249
+ origin_span = span_from_context(origin)
250
+ elif context is not None:
251
+ origin_span = span_from_context(context)
252
+ else:
253
+ origin_span = None
254
+
255
+ if secondary_context is not None:
256
+ assert origin_span is not None
257
+ origin_span = itertools.chain(origin_span, span_from_context(secondary_context))
258
+
259
+ self.errors.report(
260
+ context.line if context else -1,
261
+ context.column if context else -1,
262
+ msg,
263
+ severity=severity,
264
+ file=file,
265
+ offset=offset,
266
+ origin_span=origin_span,
267
+ end_line=context.end_line if context else -1,
268
+ end_column=context.end_column if context else -1,
269
+ code=code,
270
+ allow_dups=allow_dups,
271
+ )
272
+
273
+ def fail(
274
+ self,
275
+ msg: str,
276
+ context: Context | None,
277
+ *,
278
+ code: ErrorCode | None = None,
279
+ file: str | None = None,
280
+ allow_dups: bool = False,
281
+ secondary_context: Context | None = None,
282
+ ) -> None:
283
+ """Report an error message (unless disabled)."""
284
+ self.report(
285
+ msg,
286
+ context,
287
+ "error",
288
+ code=code,
289
+ file=file,
290
+ allow_dups=allow_dups,
291
+ secondary_context=secondary_context,
292
+ )
293
+
294
+ def note(
295
+ self,
296
+ msg: str,
297
+ context: Context,
298
+ file: str | None = None,
299
+ origin: Context | None = None,
300
+ offset: int = 0,
301
+ allow_dups: bool = False,
302
+ *,
303
+ code: ErrorCode | None = None,
304
+ secondary_context: Context | None = None,
305
+ ) -> None:
306
+ """Report a note (unless disabled)."""
307
+ self.report(
308
+ msg,
309
+ context,
310
+ "note",
311
+ file=file,
312
+ origin=origin,
313
+ offset=offset,
314
+ allow_dups=allow_dups,
315
+ code=code,
316
+ secondary_context=secondary_context,
317
+ )
318
+
319
+ def note_multiline(
320
+ self,
321
+ messages: str,
322
+ context: Context,
323
+ file: str | None = None,
324
+ offset: int = 0,
325
+ allow_dups: bool = False,
326
+ code: ErrorCode | None = None,
327
+ *,
328
+ secondary_context: Context | None = None,
329
+ ) -> None:
330
+ """Report as many notes as lines in the message (unless disabled)."""
331
+ for msg in messages.splitlines():
332
+ self.report(
333
+ msg,
334
+ context,
335
+ "note",
336
+ file=file,
337
+ offset=offset,
338
+ allow_dups=allow_dups,
339
+ code=code,
340
+ secondary_context=secondary_context,
341
+ )
342
+
343
+ #
344
+ # Specific operations
345
+ #
346
+
347
+ # The following operations are for generating specific error messages. They
348
+ # get some information as arguments, and they build an error message based
349
+ # on them.
350
+
351
+ def has_no_attr(
352
+ self,
353
+ original_type: Type,
354
+ typ: Type,
355
+ member: str,
356
+ context: Context,
357
+ module_symbol_table: SymbolTable | None = None,
358
+ ) -> ErrorCode | None:
359
+ """Report a missing or non-accessible member.
360
+
361
+ original_type is the top-level type on which the error occurred.
362
+ typ is the actual type that is missing the member. These can be
363
+ different, e.g., in a union, original_type will be the union and typ
364
+ will be the specific item in the union that does not have the member
365
+ attribute.
366
+
367
+ 'module_symbol_table' is passed to this function if the type for which we
368
+ are trying to get a member was originally a module. The SymbolTable allows
369
+ us to look up and suggests attributes of the module since they are not
370
+ directly available on original_type
371
+
372
+ If member corresponds to an operator, use the corresponding operator
373
+ name in the messages. Return the error code that was produced, if any.
374
+ """
375
+ original_type = get_proper_type(original_type)
376
+ typ = get_proper_type(typ)
377
+
378
+ if isinstance(original_type, Instance) and original_type.type.has_readable_member(member):
379
+ self.fail(f'Member "{member}" is not assignable', context)
380
+ return None
381
+ elif member == "__contains__":
382
+ self.fail(
383
+ f"Unsupported right operand type for in ({format_type(original_type, self.options)})",
384
+ context,
385
+ code=codes.OPERATOR,
386
+ )
387
+ return codes.OPERATOR
388
+ elif member in op_methods.values():
389
+ # Access to a binary operator member (e.g. _add). This case does
390
+ # not handle indexing operations.
391
+ for op, method in op_methods.items():
392
+ if method == member:
393
+ self.unsupported_left_operand(op, original_type, context)
394
+ return codes.OPERATOR
395
+ elif member == "__neg__":
396
+ self.fail(
397
+ f"Unsupported operand type for unary - ({format_type(original_type, self.options)})",
398
+ context,
399
+ code=codes.OPERATOR,
400
+ )
401
+ return codes.OPERATOR
402
+ elif member == "__pos__":
403
+ self.fail(
404
+ f"Unsupported operand type for unary + ({format_type(original_type, self.options)})",
405
+ context,
406
+ code=codes.OPERATOR,
407
+ )
408
+ return codes.OPERATOR
409
+ elif member == "__invert__":
410
+ self.fail(
411
+ f"Unsupported operand type for ~ ({format_type(original_type, self.options)})",
412
+ context,
413
+ code=codes.OPERATOR,
414
+ )
415
+ return codes.OPERATOR
416
+ elif member == "__getitem__":
417
+ # Indexed get.
418
+ # TODO: Fix this consistently in format_type
419
+ if isinstance(original_type, FunctionLike) and original_type.is_type_obj():
420
+ self.fail(
421
+ "The type {} is not generic and not indexable".format(
422
+ format_type(original_type, self.options)
423
+ ),
424
+ context,
425
+ )
426
+ return None
427
+ else:
428
+ self.fail(
429
+ f"Value of type {format_type(original_type, self.options)} is not indexable",
430
+ context,
431
+ code=codes.INDEX,
432
+ )
433
+ return codes.INDEX
434
+ elif member == "__setitem__":
435
+ # Indexed set.
436
+ self.fail(
437
+ "Unsupported target for indexed assignment ({})".format(
438
+ format_type(original_type, self.options)
439
+ ),
440
+ context,
441
+ code=codes.INDEX,
442
+ )
443
+ return codes.INDEX
444
+ elif member == "__call__":
445
+ if isinstance(original_type, Instance) and (
446
+ original_type.type.fullname == "builtins.function"
447
+ ):
448
+ # "'function' not callable" is a confusing error message.
449
+ # Explain that the problem is that the type of the function is not known.
450
+ self.fail("Cannot call function of unknown type", context, code=codes.OPERATOR)
451
+ return codes.OPERATOR
452
+ else:
453
+ self.fail(
454
+ message_registry.NOT_CALLABLE.format(format_type(original_type, self.options)),
455
+ context,
456
+ code=codes.OPERATOR,
457
+ )
458
+ return codes.OPERATOR
459
+ else:
460
+ # The non-special case: a missing ordinary attribute.
461
+ extra = ""
462
+ if member == "__iter__":
463
+ extra = " (not iterable)"
464
+ elif member == "__aiter__":
465
+ extra = " (not async iterable)"
466
+ if not self.are_type_names_disabled():
467
+ failed = False
468
+ if isinstance(original_type, Instance) and original_type.type.names:
469
+ if (
470
+ module_symbol_table is not None
471
+ and member in module_symbol_table
472
+ and not module_symbol_table[member].module_public
473
+ ):
474
+ self.fail(
475
+ f"{format_type(original_type, self.options, module_names=True)} does not "
476
+ f'explicitly export attribute "{member}"',
477
+ context,
478
+ code=codes.ATTR_DEFINED,
479
+ )
480
+ failed = True
481
+ else:
482
+ alternatives = set(original_type.type.names.keys())
483
+ if module_symbol_table is not None:
484
+ alternatives |= {
485
+ k for k, v in module_symbol_table.items() if v.module_public
486
+ }
487
+ # Rare but possible, see e.g. testNewAnalyzerCyclicDefinitionCrossModule
488
+ alternatives.discard(member)
489
+
490
+ matches = [m for m in COMMON_MISTAKES.get(member, []) if m in alternatives]
491
+ matches.extend(best_matches(member, alternatives, n=3))
492
+ if member == "__aiter__" and matches == ["__iter__"]:
493
+ matches = [] # Avoid misleading suggestion
494
+ if matches:
495
+ self.fail(
496
+ '{} has no attribute "{}"; maybe {}?{}'.format(
497
+ format_type(original_type, self.options),
498
+ member,
499
+ pretty_seq(matches, "or"),
500
+ extra,
501
+ ),
502
+ context,
503
+ code=codes.ATTR_DEFINED,
504
+ )
505
+ failed = True
506
+ if not failed:
507
+ self.fail(
508
+ '{} has no attribute "{}"{}'.format(
509
+ format_type(original_type, self.options), member, extra
510
+ ),
511
+ context,
512
+ code=codes.ATTR_DEFINED,
513
+ )
514
+ return codes.ATTR_DEFINED
515
+ elif isinstance(original_type, UnionType):
516
+ # The checker passes "object" in lieu of "None" for attribute
517
+ # checks, so we manually convert it back.
518
+ typ_format, orig_type_format = format_type_distinctly(
519
+ typ, original_type, options=self.options
520
+ )
521
+ if typ_format == '"object"' and any(
522
+ type(item) == NoneType for item in original_type.items
523
+ ):
524
+ typ_format = '"None"'
525
+ self.fail(
526
+ 'Item {} of {} has no attribute "{}"{}'.format(
527
+ typ_format, orig_type_format, member, extra
528
+ ),
529
+ context,
530
+ code=codes.UNION_ATTR,
531
+ )
532
+ return codes.UNION_ATTR
533
+ elif isinstance(original_type, TypeVarType):
534
+ bound = get_proper_type(original_type.upper_bound)
535
+ if isinstance(bound, UnionType):
536
+ typ_fmt, bound_fmt = format_type_distinctly(typ, bound, options=self.options)
537
+ original_type_fmt = format_type(original_type, self.options)
538
+ self.fail(
539
+ "Item {} of the upper bound {} of type variable {} has no "
540
+ 'attribute "{}"{}'.format(
541
+ typ_fmt, bound_fmt, original_type_fmt, member, extra
542
+ ),
543
+ context,
544
+ code=codes.UNION_ATTR,
545
+ )
546
+ return codes.UNION_ATTR
547
+ else:
548
+ self.fail(
549
+ '{} has no attribute "{}"{}'.format(
550
+ format_type(original_type, self.options), member, extra
551
+ ),
552
+ context,
553
+ code=codes.ATTR_DEFINED,
554
+ )
555
+ return codes.ATTR_DEFINED
556
+ return None
557
+
558
+ def unsupported_operand_types(
559
+ self,
560
+ op: str,
561
+ left_type: Any,
562
+ right_type: Any,
563
+ context: Context,
564
+ *,
565
+ code: ErrorCode = codes.OPERATOR,
566
+ ) -> None:
567
+ """Report unsupported operand types for a binary operation.
568
+
569
+ Types can be Type objects or strings.
570
+ """
571
+ left_str = ""
572
+ if isinstance(left_type, str):
573
+ left_str = left_type
574
+ else:
575
+ left_str = format_type(left_type, self.options)
576
+
577
+ right_str = ""
578
+ if isinstance(right_type, str):
579
+ right_str = right_type
580
+ else:
581
+ right_str = format_type(right_type, self.options)
582
+
583
+ if self.are_type_names_disabled():
584
+ msg = f"Unsupported operand types for {op} (likely involving Union)"
585
+ else:
586
+ msg = f"Unsupported operand types for {op} ({left_str} and {right_str})"
587
+ self.fail(msg, context, code=code)
588
+
589
+ def unsupported_left_operand(self, op: str, typ: Type, context: Context) -> None:
590
+ if self.are_type_names_disabled():
591
+ msg = f"Unsupported left operand type for {op} (some union)"
592
+ else:
593
+ msg = f"Unsupported left operand type for {op} ({format_type(typ, self.options)})"
594
+ self.fail(msg, context, code=codes.OPERATOR)
595
+
596
+ def not_callable(self, typ: Type, context: Context) -> Type:
597
+ self.fail(message_registry.NOT_CALLABLE.format(format_type(typ, self.options)), context)
598
+ return AnyType(TypeOfAny.from_error)
599
+
600
+ def untyped_function_call(self, callee: CallableType, context: Context) -> Type:
601
+ name = callable_name(callee) or "(unknown)"
602
+ self.fail(
603
+ f"Call to untyped function {name} in typed context",
604
+ context,
605
+ code=codes.NO_UNTYPED_CALL,
606
+ )
607
+ return AnyType(TypeOfAny.from_error)
608
+
609
+ def incompatible_argument(
610
+ self,
611
+ n: int,
612
+ m: int,
613
+ callee: CallableType,
614
+ arg_type: Type,
615
+ arg_kind: ArgKind,
616
+ object_type: Type | None,
617
+ context: Context,
618
+ outer_context: Context,
619
+ ) -> ErrorCode | None:
620
+ """Report an error about an incompatible argument type.
621
+
622
+ The argument type is arg_type, argument number is n and the
623
+ callee type is 'callee'. If the callee represents a method
624
+ that corresponds to an operator, use the corresponding
625
+ operator name in the messages.
626
+
627
+ Return the error code that used for the argument (multiple error
628
+ codes are possible).
629
+ """
630
+ arg_type = get_proper_type(arg_type)
631
+
632
+ target = ""
633
+ callee_name = callable_name(callee)
634
+ if callee_name is not None:
635
+ name = callee_name
636
+ if callee.bound_args and callee.bound_args[0] is not None:
637
+ base = format_type(callee.bound_args[0], self.options)
638
+ else:
639
+ base = extract_type(name)
640
+
641
+ for method, op in op_methods_to_symbols.items():
642
+ for variant in method, "__r" + method[2:]:
643
+ # FIX: do not rely on textual formatting
644
+ if name.startswith(f'"{variant}" of'):
645
+ if op == "in" or variant != method:
646
+ # Reversed order of base/argument.
647
+ self.unsupported_operand_types(
648
+ op, arg_type, base, context, code=codes.OPERATOR
649
+ )
650
+ else:
651
+ self.unsupported_operand_types(
652
+ op, base, arg_type, context, code=codes.OPERATOR
653
+ )
654
+ return codes.OPERATOR
655
+
656
+ if name.startswith('"__getitem__" of'):
657
+ self.invalid_index_type(
658
+ arg_type, callee.arg_types[n - 1], base, context, code=codes.INDEX
659
+ )
660
+ return codes.INDEX
661
+
662
+ if name.startswith('"__setitem__" of'):
663
+ if n == 1:
664
+ self.invalid_index_type(
665
+ arg_type, callee.arg_types[n - 1], base, context, code=codes.INDEX
666
+ )
667
+ return codes.INDEX
668
+ else:
669
+ arg_type_str, callee_type_str = format_type_distinctly(
670
+ arg_type, callee.arg_types[n - 1], options=self.options
671
+ )
672
+ info = (
673
+ f" (expression has type {arg_type_str}, "
674
+ f"target has type {callee_type_str})"
675
+ )
676
+ error_msg = (
677
+ message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT.with_additional_msg(info)
678
+ )
679
+ self.fail(error_msg.value, context, code=error_msg.code)
680
+ return error_msg.code
681
+
682
+ target = f"to {name} "
683
+
684
+ msg = ""
685
+ code = codes.MISC
686
+ notes: list[str] = []
687
+ if callee_name == "<list>":
688
+ name = callee_name[1:-1]
689
+ n -= 1
690
+ actual_type_str, expected_type_str = format_type_distinctly(
691
+ arg_type, callee.arg_types[0], options=self.options
692
+ )
693
+ msg = "{} item {} has incompatible type {}; expected {}".format(
694
+ name.title(), n, actual_type_str, expected_type_str
695
+ )
696
+ code = codes.LIST_ITEM
697
+ elif callee_name == "<dict>" and isinstance(
698
+ get_proper_type(callee.arg_types[n - 1]), TupleType
699
+ ):
700
+ name = callee_name[1:-1]
701
+ n -= 1
702
+ key_type, value_type = cast(TupleType, arg_type).items
703
+ expected_key_type, expected_value_type = cast(TupleType, callee.arg_types[n]).items
704
+
705
+ # don't increase verbosity unless there is need to do so
706
+ if is_subtype(key_type, expected_key_type):
707
+ key_type_str = format_type(key_type, self.options)
708
+ expected_key_type_str = format_type(expected_key_type, self.options)
709
+ else:
710
+ key_type_str, expected_key_type_str = format_type_distinctly(
711
+ key_type, expected_key_type, options=self.options
712
+ )
713
+ if is_subtype(value_type, expected_value_type):
714
+ value_type_str = format_type(value_type, self.options)
715
+ expected_value_type_str = format_type(expected_value_type, self.options)
716
+ else:
717
+ value_type_str, expected_value_type_str = format_type_distinctly(
718
+ value_type, expected_value_type, options=self.options
719
+ )
720
+
721
+ msg = "{} entry {} has incompatible type {}: {}; expected {}: {}".format(
722
+ name.title(),
723
+ n,
724
+ key_type_str,
725
+ value_type_str,
726
+ expected_key_type_str,
727
+ expected_value_type_str,
728
+ )
729
+ code = codes.DICT_ITEM
730
+ elif callee_name == "<dict>":
731
+ value_type_str, expected_value_type_str = format_type_distinctly(
732
+ arg_type, callee.arg_types[n - 1], options=self.options
733
+ )
734
+ msg = "Unpacked dict entry {} has incompatible type {}; expected {}".format(
735
+ n - 1, value_type_str, expected_value_type_str
736
+ )
737
+ code = codes.DICT_ITEM
738
+ elif callee_name == "<list-comprehension>":
739
+ actual_type_str, expected_type_str = map(
740
+ strip_quotes,
741
+ format_type_distinctly(arg_type, callee.arg_types[0], options=self.options),
742
+ )
743
+ msg = "List comprehension has incompatible type List[{}]; expected List[{}]".format(
744
+ actual_type_str, expected_type_str
745
+ )
746
+ elif callee_name == "<set-comprehension>":
747
+ actual_type_str, expected_type_str = map(
748
+ strip_quotes,
749
+ format_type_distinctly(arg_type, callee.arg_types[0], options=self.options),
750
+ )
751
+ msg = "Set comprehension has incompatible type Set[{}]; expected Set[{}]".format(
752
+ actual_type_str, expected_type_str
753
+ )
754
+ elif callee_name == "<dictionary-comprehension>":
755
+ actual_type_str, expected_type_str = format_type_distinctly(
756
+ arg_type, callee.arg_types[n - 1], options=self.options
757
+ )
758
+ msg = (
759
+ "{} expression in dictionary comprehension has incompatible type {}; "
760
+ "expected type {}"
761
+ ).format("Key" if n == 1 else "Value", actual_type_str, expected_type_str)
762
+ elif callee_name == "<generator>":
763
+ actual_type_str, expected_type_str = format_type_distinctly(
764
+ arg_type, callee.arg_types[0], options=self.options
765
+ )
766
+ msg = "Generator has incompatible item type {}; expected {}".format(
767
+ actual_type_str, expected_type_str
768
+ )
769
+ else:
770
+ if self.prefer_simple_messages():
771
+ msg = "Argument has incompatible type"
772
+ else:
773
+ try:
774
+ expected_type = callee.arg_types[m - 1]
775
+ except IndexError: # Varargs callees
776
+ expected_type = callee.arg_types[-1]
777
+ arg_type_str, expected_type_str = format_type_distinctly(
778
+ arg_type, expected_type, bare=True, options=self.options
779
+ )
780
+ if arg_kind == ARG_STAR:
781
+ arg_type_str = "*" + arg_type_str
782
+ elif arg_kind == ARG_STAR2:
783
+ arg_type_str = "**" + arg_type_str
784
+
785
+ # For function calls with keyword arguments, display the argument name rather
786
+ # than the number.
787
+ arg_label = str(n)
788
+ if isinstance(outer_context, CallExpr) and len(outer_context.arg_names) >= n:
789
+ arg_name = outer_context.arg_names[n - 1]
790
+ if arg_name is not None:
791
+ arg_label = f'"{arg_name}"'
792
+ if (
793
+ arg_kind == ARG_STAR2
794
+ and isinstance(arg_type, TypedDictType)
795
+ and m <= len(callee.arg_names)
796
+ and callee.arg_names[m - 1] is not None
797
+ and callee.arg_kinds[m - 1] != ARG_STAR2
798
+ ):
799
+ arg_name = callee.arg_names[m - 1]
800
+ assert arg_name is not None
801
+ arg_type_str, expected_type_str = format_type_distinctly(
802
+ arg_type.items[arg_name], expected_type, bare=True, options=self.options
803
+ )
804
+ arg_label = f'"{arg_name}"'
805
+ if isinstance(outer_context, IndexExpr) and isinstance(
806
+ outer_context.index, StrExpr
807
+ ):
808
+ msg = 'Value of "{}" has incompatible type {}; expected {}'.format(
809
+ outer_context.index.value,
810
+ quote_type_string(arg_type_str),
811
+ quote_type_string(expected_type_str),
812
+ )
813
+ else:
814
+ msg = "Argument {} {}has incompatible type {}; expected {}".format(
815
+ arg_label,
816
+ target,
817
+ quote_type_string(arg_type_str),
818
+ quote_type_string(expected_type_str),
819
+ )
820
+ expected_type = get_proper_type(expected_type)
821
+ if isinstance(expected_type, UnionType):
822
+ expected_types = list(expected_type.items)
823
+ else:
824
+ expected_types = [expected_type]
825
+ for type in get_proper_types(expected_types):
826
+ if isinstance(arg_type, Instance) and isinstance(type, Instance):
827
+ notes = append_invariance_notes(notes, arg_type, type)
828
+ notes = append_numbers_notes(notes, arg_type, type)
829
+ object_type = get_proper_type(object_type)
830
+ if isinstance(object_type, TypedDictType):
831
+ code = codes.TYPEDDICT_ITEM
832
+ else:
833
+ code = codes.ARG_TYPE
834
+ self.fail(msg, context, code=code)
835
+ if notes:
836
+ for note_msg in notes:
837
+ self.note(note_msg, context, code=code)
838
+ return code
839
+
840
+ def incompatible_argument_note(
841
+ self,
842
+ original_caller_type: ProperType,
843
+ callee_type: ProperType,
844
+ context: Context,
845
+ code: ErrorCode | None,
846
+ ) -> None:
847
+ if self.prefer_simple_messages():
848
+ return
849
+ if isinstance(
850
+ original_caller_type, (Instance, TupleType, TypedDictType, TypeType, CallableType)
851
+ ):
852
+ if isinstance(callee_type, Instance) and callee_type.type.is_protocol:
853
+ self.report_protocol_problems(
854
+ original_caller_type, callee_type, context, code=code
855
+ )
856
+ if isinstance(callee_type, UnionType):
857
+ for item in callee_type.items:
858
+ item = get_proper_type(item)
859
+ if isinstance(item, Instance) and item.type.is_protocol:
860
+ self.report_protocol_problems(
861
+ original_caller_type, item, context, code=code
862
+ )
863
+ if isinstance(callee_type, CallableType) and isinstance(original_caller_type, Instance):
864
+ call = find_member(
865
+ "__call__", original_caller_type, original_caller_type, is_operator=True
866
+ )
867
+ if call:
868
+ self.note_call(original_caller_type, call, context, code=code)
869
+
870
+ self.maybe_note_concatenate_pos_args(original_caller_type, callee_type, context, code)
871
+
872
+ def maybe_note_concatenate_pos_args(
873
+ self,
874
+ original_caller_type: ProperType,
875
+ callee_type: ProperType,
876
+ context: Context,
877
+ code: ErrorCode | None = None,
878
+ ) -> None:
879
+ # pos-only vs positional can be confusing, with Concatenate
880
+ if (
881
+ isinstance(callee_type, CallableType)
882
+ and isinstance(original_caller_type, CallableType)
883
+ and (original_caller_type.from_concatenate or callee_type.from_concatenate)
884
+ ):
885
+ names: list[str] = []
886
+ for c, o in zip(
887
+ callee_type.formal_arguments(), original_caller_type.formal_arguments()
888
+ ):
889
+ if None in (c.pos, o.pos):
890
+ # non-positional
891
+ continue
892
+ if c.name != o.name and c.name is None and o.name is not None:
893
+ names.append(o.name)
894
+
895
+ if names:
896
+ missing_arguments = '"' + '", "'.join(names) + '"'
897
+ self.note(
898
+ f'This is likely because "{original_caller_type.name}" has named arguments: '
899
+ f"{missing_arguments}. Consider marking them positional-only",
900
+ context,
901
+ code=code,
902
+ )
903
+
904
+ def invalid_index_type(
905
+ self,
906
+ index_type: Type,
907
+ expected_type: Type,
908
+ base_str: str,
909
+ context: Context,
910
+ *,
911
+ code: ErrorCode,
912
+ ) -> None:
913
+ index_str, expected_str = format_type_distinctly(
914
+ index_type, expected_type, options=self.options
915
+ )
916
+ self.fail(
917
+ "Invalid index type {} for {}; expected type {}".format(
918
+ index_str, base_str, expected_str
919
+ ),
920
+ context,
921
+ code=code,
922
+ )
923
+
924
+ def too_few_arguments(
925
+ self, callee: CallableType, context: Context, argument_names: Sequence[str | None] | None
926
+ ) -> None:
927
+ if self.prefer_simple_messages():
928
+ msg = "Too few arguments"
929
+ elif argument_names is not None:
930
+ num_positional_args = sum(k is None for k in argument_names)
931
+ arguments_left = callee.arg_names[num_positional_args : callee.min_args]
932
+ diff = [k for k in arguments_left if k not in argument_names]
933
+ if len(diff) == 1:
934
+ msg = "Missing positional argument"
935
+ else:
936
+ msg = "Missing positional arguments"
937
+ callee_name = callable_name(callee)
938
+ if callee_name is not None and diff and all(d is not None for d in diff):
939
+ args = '", "'.join(cast(List[str], diff))
940
+ msg += f' "{args}" in call to {callee_name}'
941
+ else:
942
+ msg = "Too few arguments" + for_function(callee)
943
+
944
+ else:
945
+ msg = "Too few arguments" + for_function(callee)
946
+ self.fail(msg, context, code=codes.CALL_ARG)
947
+
948
+ def missing_named_argument(self, callee: CallableType, context: Context, name: str) -> None:
949
+ msg = f'Missing named argument "{name}"' + for_function(callee)
950
+ self.fail(msg, context, code=codes.CALL_ARG)
951
+
952
+ def too_many_arguments(self, callee: CallableType, context: Context) -> None:
953
+ if self.prefer_simple_messages():
954
+ msg = "Too many arguments"
955
+ else:
956
+ msg = "Too many arguments" + for_function(callee)
957
+ self.fail(msg, context, code=codes.CALL_ARG)
958
+ self.maybe_note_about_special_args(callee, context)
959
+
960
+ def too_many_arguments_from_typed_dict(
961
+ self, callee: CallableType, arg_type: TypedDictType, context: Context
962
+ ) -> None:
963
+ # Try to determine the name of the extra argument.
964
+ for key in arg_type.items:
965
+ if key not in callee.arg_names:
966
+ msg = f'Extra argument "{key}" from **args' + for_function(callee)
967
+ break
968
+ else:
969
+ self.too_many_arguments(callee, context)
970
+ return
971
+ self.fail(msg, context)
972
+
973
+ def too_many_positional_arguments(self, callee: CallableType, context: Context) -> None:
974
+ if self.prefer_simple_messages():
975
+ msg = "Too many positional arguments"
976
+ else:
977
+ msg = "Too many positional arguments" + for_function(callee)
978
+ self.fail(msg, context)
979
+ self.maybe_note_about_special_args(callee, context)
980
+
981
+ def maybe_note_about_special_args(self, callee: CallableType, context: Context) -> None:
982
+ if self.prefer_simple_messages():
983
+ return
984
+ # https://github.com/python/mypy/issues/11309
985
+ first_arg = callee.def_extras.get("first_arg")
986
+ if first_arg and first_arg not in {"self", "cls", "mcs"}:
987
+ self.note(
988
+ "Looks like the first special argument in a method "
989
+ 'is not named "self", "cls", or "mcs", '
990
+ "maybe it is missing?",
991
+ context,
992
+ )
993
+
994
+ def unexpected_keyword_argument_for_function(
995
+ self, for_func: str, name: str, context: Context, *, matches: list[str] | None = None
996
+ ) -> None:
997
+ msg = f'Unexpected keyword argument "{name}"' + for_func
998
+ if matches:
999
+ msg += f"; did you mean {pretty_seq(matches, 'or')}?"
1000
+ self.fail(msg, context, code=codes.CALL_ARG)
1001
+
1002
+ def unexpected_keyword_argument(
1003
+ self, callee: CallableType, name: str, arg_type: Type, context: Context
1004
+ ) -> None:
1005
+ # Suggest intended keyword, look for type match else fallback on any match.
1006
+ matching_type_args = []
1007
+ not_matching_type_args = []
1008
+ for i, kwarg_type in enumerate(callee.arg_types):
1009
+ callee_arg_name = callee.arg_names[i]
1010
+ if callee_arg_name is not None and callee.arg_kinds[i] != ARG_STAR:
1011
+ if is_subtype(arg_type, kwarg_type):
1012
+ matching_type_args.append(callee_arg_name)
1013
+ else:
1014
+ not_matching_type_args.append(callee_arg_name)
1015
+ matches = best_matches(name, matching_type_args, n=3)
1016
+ if not matches:
1017
+ matches = best_matches(name, not_matching_type_args, n=3)
1018
+ self.unexpected_keyword_argument_for_function(
1019
+ for_function(callee), name, context, matches=matches
1020
+ )
1021
+ module = find_defining_module(self.modules, callee)
1022
+ if module:
1023
+ assert callee.definition is not None
1024
+ fname = callable_name(callee)
1025
+ if not fname: # an alias to function with a different name
1026
+ fname = "Called function"
1027
+ self.note(
1028
+ f"{fname} defined here",
1029
+ callee.definition,
1030
+ file=module.path,
1031
+ origin=context,
1032
+ code=codes.CALL_ARG,
1033
+ )
1034
+
1035
+ def duplicate_argument_value(self, callee: CallableType, index: int, context: Context) -> None:
1036
+ self.fail(
1037
+ '{} gets multiple values for keyword argument "{}"'.format(
1038
+ callable_name(callee) or "Function", callee.arg_names[index]
1039
+ ),
1040
+ context,
1041
+ )
1042
+
1043
+ def does_not_return_value(self, callee_type: Type | None, context: Context) -> None:
1044
+ """Report an error about use of an unusable type."""
1045
+ callee_type = get_proper_type(callee_type)
1046
+ callee_name = callable_name(callee_type) if isinstance(callee_type, FunctionLike) else None
1047
+ name = callee_name or "Function"
1048
+ message = f"{name} does not return a value (it only ever returns None)"
1049
+ self.fail(message, context, code=codes.FUNC_RETURNS_VALUE)
1050
+
1051
+ def deleted_as_rvalue(self, typ: DeletedType, context: Context) -> None:
1052
+ """Report an error about using an deleted type as an rvalue."""
1053
+ if typ.source is None:
1054
+ s = ""
1055
+ else:
1056
+ s = f' "{typ.source}"'
1057
+ self.fail(f"Trying to read deleted variable{s}", context)
1058
+
1059
+ def deleted_as_lvalue(self, typ: DeletedType, context: Context) -> None:
1060
+ """Report an error about using an deleted type as an lvalue.
1061
+
1062
+ Currently, this only occurs when trying to assign to an
1063
+ exception variable outside the local except: blocks.
1064
+ """
1065
+ if typ.source is None:
1066
+ s = ""
1067
+ else:
1068
+ s = f' "{typ.source}"'
1069
+ self.fail(f"Assignment to variable{s} outside except: block", context)
1070
+
1071
+ def no_variant_matches_arguments(
1072
+ self,
1073
+ overload: Overloaded,
1074
+ arg_types: list[Type],
1075
+ context: Context,
1076
+ *,
1077
+ code: ErrorCode | None = None,
1078
+ ) -> None:
1079
+ code = code or codes.CALL_OVERLOAD
1080
+ name = callable_name(overload)
1081
+ if name:
1082
+ name_str = f" of {name}"
1083
+ else:
1084
+ name_str = ""
1085
+ arg_types_str = ", ".join(format_type(arg, self.options) for arg in arg_types)
1086
+ num_args = len(arg_types)
1087
+ if num_args == 0:
1088
+ self.fail(
1089
+ f"All overload variants{name_str} require at least one argument",
1090
+ context,
1091
+ code=code,
1092
+ )
1093
+ elif num_args == 1:
1094
+ self.fail(
1095
+ f"No overload variant{name_str} matches argument type {arg_types_str}",
1096
+ context,
1097
+ code=code,
1098
+ )
1099
+ else:
1100
+ self.fail(
1101
+ f"No overload variant{name_str} matches argument types {arg_types_str}",
1102
+ context,
1103
+ code=code,
1104
+ )
1105
+
1106
+ self.note(f"Possible overload variant{plural_s(len(overload.items))}:", context, code=code)
1107
+ for item in overload.items:
1108
+ self.note(pretty_callable(item, self.options), context, offset=4, code=code)
1109
+
1110
+ def wrong_number_values_to_unpack(
1111
+ self, provided: int, expected: int, context: Context
1112
+ ) -> None:
1113
+ if provided < expected:
1114
+ if provided == 1:
1115
+ self.fail(f"Need more than 1 value to unpack ({expected} expected)", context)
1116
+ else:
1117
+ self.fail(
1118
+ f"Need more than {provided} values to unpack ({expected} expected)", context
1119
+ )
1120
+ elif provided > expected:
1121
+ self.fail(
1122
+ f"Too many values to unpack ({expected} expected, {provided} provided)", context
1123
+ )
1124
+
1125
+ def unpacking_strings_disallowed(self, context: Context) -> None:
1126
+ self.fail("Unpacking a string is disallowed", context)
1127
+
1128
+ def type_not_iterable(self, type: Type, context: Context) -> None:
1129
+ self.fail(f"{format_type(type, self.options)} object is not iterable", context)
1130
+
1131
+ def possible_missing_await(self, context: Context, code: ErrorCode | None) -> None:
1132
+ self.note('Maybe you forgot to use "await"?', context, code=code)
1133
+
1134
+ def incompatible_operator_assignment(self, op: str, context: Context) -> None:
1135
+ self.fail(f"Result type of {op} incompatible in assignment", context)
1136
+
1137
+ def overload_signature_incompatible_with_supertype(
1138
+ self, name: str, name_in_super: str, supertype: str, context: Context
1139
+ ) -> None:
1140
+ target = self.override_target(name, name_in_super, supertype)
1141
+ self.fail(
1142
+ f'Signature of "{name}" incompatible with {target}', context, code=codes.OVERRIDE
1143
+ )
1144
+
1145
+ note_template = 'Overload variants must be defined in the same order as they are in "{}"'
1146
+ self.note(note_template.format(supertype), context, code=codes.OVERRIDE)
1147
+
1148
+ def signature_incompatible_with_supertype(
1149
+ self,
1150
+ name: str,
1151
+ name_in_super: str,
1152
+ supertype: str,
1153
+ context: Context,
1154
+ *,
1155
+ original: ProperType,
1156
+ override: ProperType,
1157
+ ) -> None:
1158
+ code = codes.OVERRIDE
1159
+ target = self.override_target(name, name_in_super, supertype)
1160
+ self.fail(f'Signature of "{name}" incompatible with {target}', context, code=code)
1161
+
1162
+ original_str, override_str = format_type_distinctly(
1163
+ original, override, options=self.options, bare=True
1164
+ )
1165
+
1166
+ INCLUDE_DECORATOR = True # Include @classmethod and @staticmethod decorators, if any
1167
+ ALLOW_DUPS = True # Allow duplicate notes, needed when signatures are duplicates
1168
+ ALIGN_OFFSET = 1 # One space, to account for the difference between error and note
1169
+ OFFSET = 4 # Four spaces, so that notes will look like this:
1170
+ # error: Signature of "f" incompatible with supertype "A"
1171
+ # note: Superclass:
1172
+ # note: def f(self) -> str
1173
+ # note: Subclass:
1174
+ # note: def f(self, x: str) -> None
1175
+ self.note(
1176
+ "Superclass:", context, offset=ALIGN_OFFSET + OFFSET, allow_dups=ALLOW_DUPS, code=code
1177
+ )
1178
+ if isinstance(original, (CallableType, Overloaded)):
1179
+ self.pretty_callable_or_overload(
1180
+ original,
1181
+ context,
1182
+ offset=ALIGN_OFFSET + 2 * OFFSET,
1183
+ add_class_or_static_decorator=INCLUDE_DECORATOR,
1184
+ allow_dups=ALLOW_DUPS,
1185
+ code=code,
1186
+ )
1187
+ else:
1188
+ self.note(
1189
+ original_str,
1190
+ context,
1191
+ offset=ALIGN_OFFSET + 2 * OFFSET,
1192
+ allow_dups=ALLOW_DUPS,
1193
+ code=code,
1194
+ )
1195
+
1196
+ self.note(
1197
+ "Subclass:", context, offset=ALIGN_OFFSET + OFFSET, allow_dups=ALLOW_DUPS, code=code
1198
+ )
1199
+ if isinstance(override, (CallableType, Overloaded)):
1200
+ self.pretty_callable_or_overload(
1201
+ override,
1202
+ context,
1203
+ offset=ALIGN_OFFSET + 2 * OFFSET,
1204
+ add_class_or_static_decorator=INCLUDE_DECORATOR,
1205
+ allow_dups=ALLOW_DUPS,
1206
+ code=code,
1207
+ )
1208
+ else:
1209
+ self.note(
1210
+ override_str,
1211
+ context,
1212
+ offset=ALIGN_OFFSET + 2 * OFFSET,
1213
+ allow_dups=ALLOW_DUPS,
1214
+ code=code,
1215
+ )
1216
+
1217
+ def pretty_callable_or_overload(
1218
+ self,
1219
+ tp: CallableType | Overloaded,
1220
+ context: Context,
1221
+ *,
1222
+ offset: int = 0,
1223
+ add_class_or_static_decorator: bool = False,
1224
+ allow_dups: bool = False,
1225
+ code: ErrorCode | None = None,
1226
+ ) -> None:
1227
+ if isinstance(tp, CallableType):
1228
+ if add_class_or_static_decorator:
1229
+ decorator = pretty_class_or_static_decorator(tp)
1230
+ if decorator is not None:
1231
+ self.note(decorator, context, offset=offset, allow_dups=allow_dups, code=code)
1232
+ self.note(
1233
+ pretty_callable(tp, self.options),
1234
+ context,
1235
+ offset=offset,
1236
+ allow_dups=allow_dups,
1237
+ code=code,
1238
+ )
1239
+ elif isinstance(tp, Overloaded):
1240
+ self.pretty_overload(
1241
+ tp,
1242
+ context,
1243
+ offset,
1244
+ add_class_or_static_decorator=add_class_or_static_decorator,
1245
+ allow_dups=allow_dups,
1246
+ code=code,
1247
+ )
1248
+
1249
+ def argument_incompatible_with_supertype(
1250
+ self,
1251
+ arg_num: int,
1252
+ name: str,
1253
+ type_name: str | None,
1254
+ name_in_supertype: str,
1255
+ arg_type_in_supertype: Type,
1256
+ supertype: str,
1257
+ context: Context,
1258
+ secondary_context: Context,
1259
+ ) -> None:
1260
+ target = self.override_target(name, name_in_supertype, supertype)
1261
+ arg_type_in_supertype_f = format_type_bare(arg_type_in_supertype, self.options)
1262
+ self.fail(
1263
+ 'Argument {} of "{}" is incompatible with {}; '
1264
+ 'supertype defines the argument type as "{}"'.format(
1265
+ arg_num, name, target, arg_type_in_supertype_f
1266
+ ),
1267
+ context,
1268
+ code=codes.OVERRIDE,
1269
+ secondary_context=secondary_context,
1270
+ )
1271
+ if name != "__post_init__":
1272
+ # `__post_init__` is special, it can be incompatible by design.
1273
+ # So, this note is misleading.
1274
+ self.note(
1275
+ "This violates the Liskov substitution principle",
1276
+ context,
1277
+ code=codes.OVERRIDE,
1278
+ secondary_context=secondary_context,
1279
+ )
1280
+ self.note(
1281
+ "See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides",
1282
+ context,
1283
+ code=codes.OVERRIDE,
1284
+ secondary_context=secondary_context,
1285
+ )
1286
+
1287
+ if name == "__eq__" and type_name:
1288
+ multiline_msg = self.comparison_method_example_msg(class_name=type_name)
1289
+ self.note_multiline(
1290
+ multiline_msg, context, code=codes.OVERRIDE, secondary_context=secondary_context
1291
+ )
1292
+
1293
+ def comparison_method_example_msg(self, class_name: str) -> str:
1294
+ return dedent(
1295
+ """\
1296
+ It is recommended for "__eq__" to work with arbitrary objects, for example:
1297
+ def __eq__(self, other: object) -> bool:
1298
+ if not isinstance(other, {class_name}):
1299
+ return NotImplemented
1300
+ return <logic to compare two {class_name} instances>
1301
+ """.format(
1302
+ class_name=class_name
1303
+ )
1304
+ )
1305
+
1306
+ def return_type_incompatible_with_supertype(
1307
+ self,
1308
+ name: str,
1309
+ name_in_supertype: str,
1310
+ supertype: str,
1311
+ original: Type,
1312
+ override: Type,
1313
+ context: Context,
1314
+ ) -> None:
1315
+ target = self.override_target(name, name_in_supertype, supertype)
1316
+ override_str, original_str = format_type_distinctly(
1317
+ override, original, options=self.options
1318
+ )
1319
+ self.fail(
1320
+ 'Return type {} of "{}" incompatible with return type {} in {}'.format(
1321
+ override_str, name, original_str, target
1322
+ ),
1323
+ context,
1324
+ code=codes.OVERRIDE,
1325
+ )
1326
+
1327
+ original = get_proper_type(original)
1328
+ override = get_proper_type(override)
1329
+ if (
1330
+ isinstance(original, Instance)
1331
+ and isinstance(override, Instance)
1332
+ and override.type.fullname == "typing.AsyncIterator"
1333
+ and original.type.fullname == "typing.Coroutine"
1334
+ and len(original.args) == 3
1335
+ and original.args[2] == override
1336
+ ):
1337
+ self.note(f'Consider declaring "{name}" in {target} without "async"', context)
1338
+ self.note(
1339
+ "See https://mypy.readthedocs.io/en/stable/more_types.html#asynchronous-iterators",
1340
+ context,
1341
+ )
1342
+
1343
+ def override_target(self, name: str, name_in_super: str, supertype: str) -> str:
1344
+ target = f'supertype "{supertype}"'
1345
+ if name_in_super != name:
1346
+ target = f'"{name_in_super}" of {target}'
1347
+ return target
1348
+
1349
+ def incompatible_type_application(
1350
+ self, min_arg_count: int, max_arg_count: int, actual_arg_count: int, context: Context
1351
+ ) -> None:
1352
+ if max_arg_count == 0:
1353
+ self.fail("Type application targets a non-generic function or class", context)
1354
+ return
1355
+
1356
+ if min_arg_count == max_arg_count:
1357
+ s = f"{max_arg_count} expected"
1358
+ else:
1359
+ s = f"expected between {min_arg_count} and {max_arg_count}"
1360
+
1361
+ if actual_arg_count > max_arg_count:
1362
+ self.fail(f"Type application has too many types ({s})", context)
1363
+ else:
1364
+ self.fail(f"Type application has too few types ({s})", context)
1365
+
1366
+ def could_not_infer_type_arguments(
1367
+ self, callee_type: CallableType, n: int, context: Context
1368
+ ) -> None:
1369
+ callee_name = callable_name(callee_type)
1370
+ if callee_name is not None and n > 0:
1371
+ self.fail(f"Cannot infer type argument {n} of {callee_name}", context)
1372
+ if callee_name == "<dict>":
1373
+ # Invariance in key type causes more of these errors than we would want.
1374
+ self.note(
1375
+ "Try assigning the literal to a variable annotated as dict[<key>, <val>]",
1376
+ context,
1377
+ )
1378
+ else:
1379
+ self.fail("Cannot infer function type argument", context)
1380
+
1381
+ def invalid_var_arg(self, typ: Type, context: Context) -> None:
1382
+ self.fail("List or tuple expected as variadic arguments", context)
1383
+
1384
+ def invalid_keyword_var_arg(self, typ: Type, is_mapping: bool, context: Context) -> None:
1385
+ typ = get_proper_type(typ)
1386
+ if isinstance(typ, Instance) and is_mapping:
1387
+ self.fail("Keywords must be strings", context)
1388
+ else:
1389
+ self.fail(
1390
+ f"Argument after ** must be a mapping, not {format_type(typ, self.options)}",
1391
+ context,
1392
+ code=codes.ARG_TYPE,
1393
+ )
1394
+
1395
+ def undefined_in_superclass(self, member: str, context: Context) -> None:
1396
+ self.fail(f'"{member}" undefined in superclass', context)
1397
+
1398
+ def variable_may_be_undefined(self, name: str, context: Context) -> None:
1399
+ self.fail(f'Name "{name}" may be undefined', context, code=codes.POSSIBLY_UNDEFINED)
1400
+
1401
+ def var_used_before_def(self, name: str, context: Context) -> None:
1402
+ self.fail(f'Name "{name}" is used before definition', context, code=codes.USED_BEFORE_DEF)
1403
+
1404
+ def first_argument_for_super_must_be_type(self, actual: Type, context: Context) -> None:
1405
+ actual = get_proper_type(actual)
1406
+ if isinstance(actual, Instance):
1407
+ # Don't include type of instance, because it can look confusingly like a type
1408
+ # object.
1409
+ type_str = "a non-type instance"
1410
+ else:
1411
+ type_str = format_type(actual, self.options)
1412
+ self.fail(
1413
+ f'Argument 1 for "super" must be a type object; got {type_str}',
1414
+ context,
1415
+ code=codes.ARG_TYPE,
1416
+ )
1417
+
1418
+ def unsafe_super(self, method: str, cls: str, ctx: Context) -> None:
1419
+ self.fail(
1420
+ 'Call to abstract method "{}" of "{}" with trivial body'
1421
+ " via super() is unsafe".format(method, cls),
1422
+ ctx,
1423
+ code=codes.SAFE_SUPER,
1424
+ )
1425
+
1426
+ def too_few_string_formatting_arguments(self, context: Context) -> None:
1427
+ self.fail("Not enough arguments for format string", context, code=codes.STRING_FORMATTING)
1428
+
1429
+ def too_many_string_formatting_arguments(self, context: Context) -> None:
1430
+ self.fail(
1431
+ "Not all arguments converted during string formatting",
1432
+ context,
1433
+ code=codes.STRING_FORMATTING,
1434
+ )
1435
+
1436
+ def unsupported_placeholder(self, placeholder: str, context: Context) -> None:
1437
+ self.fail(
1438
+ f'Unsupported format character "{placeholder}"', context, code=codes.STRING_FORMATTING
1439
+ )
1440
+
1441
+ def string_interpolation_with_star_and_key(self, context: Context) -> None:
1442
+ self.fail(
1443
+ "String interpolation contains both stars and mapping keys",
1444
+ context,
1445
+ code=codes.STRING_FORMATTING,
1446
+ )
1447
+
1448
+ def requires_int_or_single_byte(self, context: Context, format_call: bool = False) -> None:
1449
+ self.fail(
1450
+ '"{}c" requires an integer in range(256) or a single byte'.format(
1451
+ ":" if format_call else "%"
1452
+ ),
1453
+ context,
1454
+ code=codes.STRING_FORMATTING,
1455
+ )
1456
+
1457
+ def requires_int_or_char(self, context: Context, format_call: bool = False) -> None:
1458
+ self.fail(
1459
+ '"{}c" requires int or char'.format(":" if format_call else "%"),
1460
+ context,
1461
+ code=codes.STRING_FORMATTING,
1462
+ )
1463
+
1464
+ def key_not_in_mapping(self, key: str, context: Context) -> None:
1465
+ self.fail(f'Key "{key}" not found in mapping', context, code=codes.STRING_FORMATTING)
1466
+
1467
+ def string_interpolation_mixing_key_and_non_keys(self, context: Context) -> None:
1468
+ self.fail(
1469
+ "String interpolation mixes specifier with and without mapping keys",
1470
+ context,
1471
+ code=codes.STRING_FORMATTING,
1472
+ )
1473
+
1474
+ def cannot_determine_type(self, name: str, context: Context) -> None:
1475
+ self.fail(f'Cannot determine type of "{name}"', context, code=codes.HAS_TYPE)
1476
+
1477
+ def cannot_determine_type_in_base(self, name: str, base: str, context: Context) -> None:
1478
+ self.fail(f'Cannot determine type of "{name}" in base class "{base}"', context)
1479
+
1480
+ def no_formal_self(self, name: str, item: CallableType, context: Context) -> None:
1481
+ type = format_type(item, self.options)
1482
+ self.fail(
1483
+ f'Attribute function "{name}" with type {type} does not accept self argument', context
1484
+ )
1485
+
1486
+ def incompatible_self_argument(
1487
+ self, name: str, arg: Type, sig: CallableType, is_classmethod: bool, context: Context
1488
+ ) -> None:
1489
+ kind = "class attribute function" if is_classmethod else "attribute function"
1490
+ arg_type = format_type(arg, self.options)
1491
+ sig_type = format_type(sig, self.options)
1492
+ self.fail(
1493
+ f'Invalid self argument {arg_type} to {kind} "{name}" with type {sig_type}', context
1494
+ )
1495
+
1496
+ def incompatible_conditional_function_def(
1497
+ self, defn: FuncDef, old_type: FunctionLike, new_type: FunctionLike
1498
+ ) -> None:
1499
+ self.fail("All conditional function variants must have identical signatures", defn)
1500
+ if isinstance(old_type, (CallableType, Overloaded)) and isinstance(
1501
+ new_type, (CallableType, Overloaded)
1502
+ ):
1503
+ self.note("Original:", defn)
1504
+ self.pretty_callable_or_overload(old_type, defn, offset=4)
1505
+ self.note("Redefinition:", defn)
1506
+ self.pretty_callable_or_overload(new_type, defn, offset=4)
1507
+
1508
+ def cannot_instantiate_abstract_class(
1509
+ self, class_name: str, abstract_attributes: dict[str, bool], context: Context
1510
+ ) -> None:
1511
+ attrs = format_string_list([f'"{a}"' for a in abstract_attributes])
1512
+ self.fail(
1513
+ f'Cannot instantiate abstract class "{class_name}" with abstract '
1514
+ f"attribute{plural_s(abstract_attributes)} {attrs}",
1515
+ context,
1516
+ code=codes.ABSTRACT,
1517
+ )
1518
+ attrs_with_none = [
1519
+ f'"{a}"'
1520
+ for a, implicit_and_can_return_none in abstract_attributes.items()
1521
+ if implicit_and_can_return_none
1522
+ ]
1523
+ if not attrs_with_none:
1524
+ return
1525
+ if len(attrs_with_none) == 1:
1526
+ note = (
1527
+ f"{attrs_with_none[0]} is implicitly abstract because it has an empty function "
1528
+ "body. If it is not meant to be abstract, explicitly `return` or `return None`."
1529
+ )
1530
+ else:
1531
+ note = (
1532
+ "The following methods were marked implicitly abstract because they have empty "
1533
+ f"function bodies: {format_string_list(attrs_with_none)}. "
1534
+ "If they are not meant to be abstract, explicitly `return` or `return None`."
1535
+ )
1536
+ self.note(note, context, code=codes.ABSTRACT)
1537
+
1538
+ def base_class_definitions_incompatible(
1539
+ self, name: str, base1: TypeInfo, base2: TypeInfo, context: Context
1540
+ ) -> None:
1541
+ self.fail(
1542
+ 'Definition of "{}" in base class "{}" is incompatible '
1543
+ 'with definition in base class "{}"'.format(name, base1.name, base2.name),
1544
+ context,
1545
+ )
1546
+
1547
+ def cant_assign_to_method(self, context: Context) -> None:
1548
+ self.fail(message_registry.CANNOT_ASSIGN_TO_METHOD, context, code=codes.METHOD_ASSIGN)
1549
+
1550
+ def cant_assign_to_classvar(self, name: str, context: Context) -> None:
1551
+ self.fail(f'Cannot assign to class variable "{name}" via instance', context)
1552
+
1553
+ def no_overridable_method(self, name: str, context: Context) -> None:
1554
+ self.fail(
1555
+ f'Method "{name}" is marked as an override, '
1556
+ "but no base method was found with this name",
1557
+ context,
1558
+ )
1559
+
1560
+ def explicit_override_decorator_missing(
1561
+ self, name: str, base_name: str, context: Context
1562
+ ) -> None:
1563
+ self.fail(
1564
+ f'Method "{name}" is not using @override '
1565
+ f'but is overriding a method in class "{base_name}"',
1566
+ context,
1567
+ code=codes.EXPLICIT_OVERRIDE_REQUIRED,
1568
+ )
1569
+
1570
+ def final_cant_override_writable(self, name: str, ctx: Context) -> None:
1571
+ self.fail(f'Cannot override writable attribute "{name}" with a final one', ctx)
1572
+
1573
+ def cant_override_final(self, name: str, base_name: str, ctx: Context) -> None:
1574
+ self.fail(
1575
+ 'Cannot override final attribute "{}"'
1576
+ ' (previously declared in base class "{}")'.format(name, base_name),
1577
+ ctx,
1578
+ )
1579
+
1580
+ def cant_assign_to_final(self, name: str, attr_assign: bool, ctx: Context) -> None:
1581
+ """Warn about a prohibited assignment to a final attribute.
1582
+
1583
+ Pass `attr_assign=True` if the assignment assigns to an attribute.
1584
+ """
1585
+ kind = "attribute" if attr_assign else "name"
1586
+ self.fail(f'Cannot assign to final {kind} "{unmangle(name)}"', ctx)
1587
+
1588
+ def protocol_members_cant_be_final(self, ctx: Context) -> None:
1589
+ self.fail("Protocol member cannot be final", ctx)
1590
+
1591
+ def final_without_value(self, ctx: Context) -> None:
1592
+ self.fail("Final name must be initialized with a value", ctx)
1593
+
1594
+ def read_only_property(self, name: str, type: TypeInfo, context: Context) -> None:
1595
+ self.fail(f'Property "{name}" defined in "{type.name}" is read-only', context)
1596
+
1597
+ def incompatible_typevar_value(
1598
+ self, callee: CallableType, typ: Type, typevar_name: str, context: Context
1599
+ ) -> None:
1600
+ self.fail(
1601
+ message_registry.INCOMPATIBLE_TYPEVAR_VALUE.format(
1602
+ typevar_name, callable_name(callee) or "function", format_type(typ, self.options)
1603
+ ),
1604
+ context,
1605
+ code=codes.TYPE_VAR,
1606
+ )
1607
+
1608
+ def dangerous_comparison(self, left: Type, right: Type, kind: str, ctx: Context) -> None:
1609
+ left_str = "element" if kind == "container" else "left operand"
1610
+ right_str = "container item" if kind == "container" else "right operand"
1611
+ message = "Non-overlapping {} check ({} type: {}, {} type: {})"
1612
+ left_typ, right_typ = format_type_distinctly(left, right, options=self.options)
1613
+ self.fail(
1614
+ message.format(kind, left_str, left_typ, right_str, right_typ),
1615
+ ctx,
1616
+ code=codes.COMPARISON_OVERLAP,
1617
+ )
1618
+
1619
+ def overload_inconsistently_applies_decorator(self, decorator: str, context: Context) -> None:
1620
+ self.fail(
1621
+ f'Overload does not consistently use the "@{decorator}" '
1622
+ + "decorator on all function signatures.",
1623
+ context,
1624
+ )
1625
+
1626
+ def overloaded_signatures_overlap(self, index1: int, index2: int, context: Context) -> None:
1627
+ self.fail(
1628
+ "Overloaded function signatures {} and {} overlap with "
1629
+ "incompatible return types".format(index1, index2),
1630
+ context,
1631
+ code=codes.OVERLOAD_OVERLAP,
1632
+ )
1633
+
1634
+ def overloaded_signature_will_never_match(
1635
+ self, index1: int, index2: int, context: Context
1636
+ ) -> None:
1637
+ self.fail(
1638
+ "Overloaded function signature {index2} will never be matched: "
1639
+ "signature {index1}'s parameter type(s) are the same or broader".format(
1640
+ index1=index1, index2=index2
1641
+ ),
1642
+ context,
1643
+ )
1644
+
1645
+ def overloaded_signatures_typevar_specific(self, index: int, context: Context) -> None:
1646
+ self.fail(
1647
+ f"Overloaded function implementation cannot satisfy signature {index} "
1648
+ + "due to inconsistencies in how they use type variables",
1649
+ context,
1650
+ )
1651
+
1652
+ def overloaded_signatures_arg_specific(self, index: int, context: Context) -> None:
1653
+ self.fail(
1654
+ "Overloaded function implementation does not accept all possible arguments "
1655
+ "of signature {}".format(index),
1656
+ context,
1657
+ )
1658
+
1659
+ def overloaded_signatures_ret_specific(self, index: int, context: Context) -> None:
1660
+ self.fail(
1661
+ "Overloaded function implementation cannot produce return type "
1662
+ "of signature {}".format(index),
1663
+ context,
1664
+ )
1665
+
1666
+ def warn_both_operands_are_from_unions(self, context: Context) -> None:
1667
+ self.note("Both left and right operands are unions", context, code=codes.OPERATOR)
1668
+
1669
+ def warn_operand_was_from_union(self, side: str, original: Type, context: Context) -> None:
1670
+ self.note(
1671
+ f"{side} operand is of type {format_type(original, self.options)}",
1672
+ context,
1673
+ code=codes.OPERATOR,
1674
+ )
1675
+
1676
+ def operator_method_signatures_overlap(
1677
+ self,
1678
+ reverse_class: TypeInfo,
1679
+ reverse_method: str,
1680
+ forward_class: Type,
1681
+ forward_method: str,
1682
+ context: Context,
1683
+ ) -> None:
1684
+ self.fail(
1685
+ 'Signatures of "{}" of "{}" and "{}" of {} '
1686
+ "are unsafely overlapping".format(
1687
+ reverse_method,
1688
+ reverse_class.name,
1689
+ forward_method,
1690
+ format_type(forward_class, self.options),
1691
+ ),
1692
+ context,
1693
+ )
1694
+
1695
+ def forward_operator_not_callable(self, forward_method: str, context: Context) -> None:
1696
+ self.fail(f'Forward operator "{forward_method}" is not callable', context)
1697
+
1698
+ def signatures_incompatible(self, method: str, other_method: str, context: Context) -> None:
1699
+ self.fail(f'Signatures of "{method}" and "{other_method}" are incompatible', context)
1700
+
1701
+ def yield_from_invalid_operand_type(self, expr: Type, context: Context) -> Type:
1702
+ text = (
1703
+ format_type(expr, self.options)
1704
+ if format_type(expr, self.options) != "object"
1705
+ else expr
1706
+ )
1707
+ self.fail(f'"yield from" can\'t be applied to {text}', context)
1708
+ return AnyType(TypeOfAny.from_error)
1709
+
1710
+ def invalid_signature(self, func_type: Type, context: Context) -> None:
1711
+ self.fail(f"Invalid signature {format_type(func_type, self.options)}", context)
1712
+
1713
+ def invalid_signature_for_special_method(
1714
+ self, func_type: Type, context: Context, method_name: str
1715
+ ) -> None:
1716
+ self.fail(
1717
+ f'Invalid signature {format_type(func_type, self.options)} for "{method_name}"',
1718
+ context,
1719
+ )
1720
+
1721
+ def reveal_type(self, typ: Type, context: Context) -> None:
1722
+ visitor = TypeStrVisitor(options=self.options)
1723
+ self.note(f'Revealed type is "{typ.accept(visitor)}"', context)
1724
+
1725
+ def reveal_locals(self, type_map: dict[str, Type | None], context: Context) -> None:
1726
+ # To ensure that the output is predictable on Python < 3.6,
1727
+ # use an ordered dictionary sorted by variable name
1728
+ sorted_locals = dict(sorted(type_map.items(), key=lambda t: t[0]))
1729
+ if sorted_locals:
1730
+ self.note("Revealed local types are:", context)
1731
+ for k, v in sorted_locals.items():
1732
+ visitor = TypeStrVisitor(options=self.options)
1733
+ self.note(f" {k}: {v.accept(visitor) if v is not None else None}", context)
1734
+ else:
1735
+ self.note("There are no locals to reveal", context)
1736
+
1737
+ def unsupported_type_type(self, item: Type, context: Context) -> None:
1738
+ self.fail(
1739
+ f'Cannot instantiate type "Type[{format_type_bare(item, self.options)}]"', context
1740
+ )
1741
+
1742
+ def redundant_cast(self, typ: Type, context: Context) -> None:
1743
+ self.fail(
1744
+ f"Redundant cast to {format_type(typ, self.options)}",
1745
+ context,
1746
+ code=codes.REDUNDANT_CAST,
1747
+ )
1748
+
1749
+ def assert_type_fail(self, source_type: Type, target_type: Type, context: Context) -> None:
1750
+ (source, target) = format_type_distinctly(source_type, target_type, options=self.options)
1751
+ self.fail(f"Expression is of type {source}, not {target}", context, code=codes.ASSERT_TYPE)
1752
+
1753
+ def unimported_type_becomes_any(self, prefix: str, typ: Type, ctx: Context) -> None:
1754
+ self.fail(
1755
+ f"{prefix} becomes {format_type(typ, self.options)} due to an unfollowed import",
1756
+ ctx,
1757
+ code=codes.NO_ANY_UNIMPORTED,
1758
+ )
1759
+
1760
+ def need_annotation_for_var(
1761
+ self, node: SymbolNode, context: Context, python_version: tuple[int, int] | None = None
1762
+ ) -> None:
1763
+ hint = ""
1764
+ pep604_supported = not python_version or python_version >= (3, 10)
1765
+ # type to recommend the user adds
1766
+ recommended_type = None
1767
+ # Only gives hint if it's a variable declaration and the partial type is a builtin type
1768
+ if python_version and isinstance(node, Var) and isinstance(node.type, PartialType):
1769
+ type_dec = "<type>"
1770
+ if not node.type.type:
1771
+ # partial None
1772
+ if pep604_supported:
1773
+ recommended_type = f"{type_dec} | None"
1774
+ else:
1775
+ recommended_type = f"Optional[{type_dec}]"
1776
+ elif node.type.type.fullname in reverse_builtin_aliases:
1777
+ # partial types other than partial None
1778
+ alias = reverse_builtin_aliases[node.type.type.fullname]
1779
+ alias = alias.split(".")[-1]
1780
+ if alias == "Dict":
1781
+ type_dec = f"{type_dec}, {type_dec}"
1782
+ recommended_type = f"{alias}[{type_dec}]"
1783
+ if recommended_type is not None:
1784
+ hint = f' (hint: "{node.name}: {recommended_type} = ...")'
1785
+
1786
+ self.fail(
1787
+ f'Need type annotation for "{unmangle(node.name)}"{hint}',
1788
+ context,
1789
+ code=codes.VAR_ANNOTATED,
1790
+ )
1791
+
1792
+ def explicit_any(self, ctx: Context) -> None:
1793
+ self.fail('Explicit "Any" is not allowed', ctx)
1794
+
1795
+ def unsupported_target_for_star_typeddict(self, typ: Type, ctx: Context) -> None:
1796
+ self.fail(
1797
+ "Unsupported type {} for ** expansion in TypedDict".format(
1798
+ format_type(typ, self.options)
1799
+ ),
1800
+ ctx,
1801
+ code=codes.TYPEDDICT_ITEM,
1802
+ )
1803
+
1804
+ def non_required_keys_absent_with_star(self, keys: list[str], ctx: Context) -> None:
1805
+ self.fail(
1806
+ "Non-required {} not explicitly found in any ** item".format(
1807
+ format_key_list(keys, short=True)
1808
+ ),
1809
+ ctx,
1810
+ code=codes.TYPEDDICT_ITEM,
1811
+ )
1812
+
1813
+ def unexpected_typeddict_keys(
1814
+ self,
1815
+ typ: TypedDictType,
1816
+ expected_keys: list[str],
1817
+ actual_keys: list[str],
1818
+ context: Context,
1819
+ ) -> None:
1820
+ actual_set = set(actual_keys)
1821
+ expected_set = set(expected_keys)
1822
+ if not typ.is_anonymous():
1823
+ # Generate simpler messages for some common special cases.
1824
+ # Use list comprehension instead of set operations to preserve order.
1825
+ missing = [key for key in expected_keys if key not in actual_set]
1826
+ if missing:
1827
+ self.fail(
1828
+ "Missing {} for TypedDict {}".format(
1829
+ format_key_list(missing, short=True), format_type(typ, self.options)
1830
+ ),
1831
+ context,
1832
+ code=codes.TYPEDDICT_ITEM,
1833
+ )
1834
+ extra = [key for key in actual_keys if key not in expected_set]
1835
+ if extra:
1836
+ self.fail(
1837
+ "Extra {} for TypedDict {}".format(
1838
+ format_key_list(extra, short=True), format_type(typ, self.options)
1839
+ ),
1840
+ context,
1841
+ code=codes.TYPEDDICT_UNKNOWN_KEY,
1842
+ )
1843
+ if missing or extra:
1844
+ # No need to check for further errors
1845
+ return
1846
+ found = format_key_list(actual_keys, short=True)
1847
+ if not expected_keys:
1848
+ self.fail(f"Unexpected TypedDict {found}", context)
1849
+ return
1850
+ expected = format_key_list(expected_keys)
1851
+ if actual_keys and actual_set < expected_set:
1852
+ found = f"only {found}"
1853
+ self.fail(f"Expected {expected} but found {found}", context, code=codes.TYPEDDICT_ITEM)
1854
+
1855
+ def typeddict_key_must_be_string_literal(self, typ: TypedDictType, context: Context) -> None:
1856
+ self.fail(
1857
+ "TypedDict key must be a string literal; expected one of {}".format(
1858
+ format_item_name_list(typ.items.keys())
1859
+ ),
1860
+ context,
1861
+ code=codes.LITERAL_REQ,
1862
+ )
1863
+
1864
+ def typeddict_key_not_found(
1865
+ self, typ: TypedDictType, item_name: str, context: Context, setitem: bool = False
1866
+ ) -> None:
1867
+ """Handle error messages for TypedDicts that have unknown keys.
1868
+
1869
+ Note, that we differentiate in between reading a value and setting a
1870
+ value.
1871
+ Setting a value on a TypedDict is an 'unknown-key' error, whereas
1872
+ reading it is the more serious/general 'item' error.
1873
+ """
1874
+ if typ.is_anonymous():
1875
+ self.fail(
1876
+ '"{}" is not a valid TypedDict key; expected one of {}'.format(
1877
+ item_name, format_item_name_list(typ.items.keys())
1878
+ ),
1879
+ context,
1880
+ )
1881
+ else:
1882
+ err_code = codes.TYPEDDICT_UNKNOWN_KEY if setitem else codes.TYPEDDICT_ITEM
1883
+ self.fail(
1884
+ f'TypedDict {format_type(typ, self.options)} has no key "{item_name}"',
1885
+ context,
1886
+ code=err_code,
1887
+ )
1888
+ matches = best_matches(item_name, typ.items.keys(), n=3)
1889
+ if matches:
1890
+ self.note(
1891
+ "Did you mean {}?".format(pretty_seq(matches, "or")), context, code=err_code
1892
+ )
1893
+
1894
+ def typeddict_context_ambiguous(self, types: list[TypedDictType], context: Context) -> None:
1895
+ formatted_types = ", ".join(list(format_type_distinctly(*types, options=self.options)))
1896
+ self.fail(
1897
+ f"Type of TypedDict is ambiguous, none of ({formatted_types}) matches cleanly", context
1898
+ )
1899
+
1900
+ def typeddict_key_cannot_be_deleted(
1901
+ self, typ: TypedDictType, item_name: str, context: Context
1902
+ ) -> None:
1903
+ if typ.is_anonymous():
1904
+ self.fail(f'TypedDict key "{item_name}" cannot be deleted', context)
1905
+ else:
1906
+ self.fail(
1907
+ f'Key "{item_name}" of TypedDict {format_type(typ, self.options)} cannot be deleted',
1908
+ context,
1909
+ )
1910
+
1911
+ def typeddict_setdefault_arguments_inconsistent(
1912
+ self, default: Type, expected: Type, context: Context
1913
+ ) -> None:
1914
+ msg = 'Argument 2 to "setdefault" of "TypedDict" has incompatible type {}; expected {}'
1915
+ self.fail(
1916
+ msg.format(format_type(default, self.options), format_type(expected, self.options)),
1917
+ context,
1918
+ code=codes.TYPEDDICT_ITEM,
1919
+ )
1920
+
1921
+ def type_arguments_not_allowed(self, context: Context) -> None:
1922
+ self.fail("Parameterized generics cannot be used with class or instance checks", context)
1923
+
1924
+ def disallowed_any_type(self, typ: Type, context: Context) -> None:
1925
+ typ = get_proper_type(typ)
1926
+ if isinstance(typ, AnyType):
1927
+ message = 'Expression has type "Any"'
1928
+ else:
1929
+ message = f'Expression type contains "Any" (has type {format_type(typ, self.options)})'
1930
+ self.fail(message, context)
1931
+
1932
+ def incorrectly_returning_any(self, typ: Type, context: Context) -> None:
1933
+ message = (
1934
+ f"Returning Any from function declared to return {format_type(typ, self.options)}"
1935
+ )
1936
+ self.fail(message, context, code=codes.NO_ANY_RETURN)
1937
+
1938
+ def incorrect__exit__return(self, context: Context) -> None:
1939
+ self.fail(
1940
+ '"bool" is invalid as return type for "__exit__" that always returns False',
1941
+ context,
1942
+ code=codes.EXIT_RETURN,
1943
+ )
1944
+ self.note(
1945
+ 'Use "typing_extensions.Literal[False]" as the return type or change it to "None"',
1946
+ context,
1947
+ code=codes.EXIT_RETURN,
1948
+ )
1949
+ self.note(
1950
+ 'If return type of "__exit__" implies that it may return True, '
1951
+ "the context manager may swallow exceptions",
1952
+ context,
1953
+ code=codes.EXIT_RETURN,
1954
+ )
1955
+
1956
+ def untyped_decorated_function(self, typ: Type, context: Context) -> None:
1957
+ typ = get_proper_type(typ)
1958
+ if isinstance(typ, AnyType):
1959
+ self.fail("Function is untyped after decorator transformation", context)
1960
+ else:
1961
+ self.fail(
1962
+ f'Type of decorated function contains type "Any" ({format_type(typ, self.options)})',
1963
+ context,
1964
+ )
1965
+
1966
+ def typed_function_untyped_decorator(self, func_name: str, context: Context) -> None:
1967
+ self.fail(f'Untyped decorator makes function "{func_name}" untyped', context)
1968
+
1969
+ def bad_proto_variance(
1970
+ self, actual: int, tvar_name: str, expected: int, context: Context
1971
+ ) -> None:
1972
+ msg = capitalize(
1973
+ '{} type variable "{}" used in protocol where'
1974
+ " {} one is expected".format(
1975
+ variance_string(actual), tvar_name, variance_string(expected)
1976
+ )
1977
+ )
1978
+ self.fail(msg, context)
1979
+
1980
+ def concrete_only_assign(self, typ: Type, context: Context) -> None:
1981
+ self.fail(
1982
+ f"Can only assign concrete classes to a variable of type {format_type(typ, self.options)}",
1983
+ context,
1984
+ code=codes.TYPE_ABSTRACT,
1985
+ )
1986
+
1987
+ def concrete_only_call(self, typ: Type, context: Context) -> None:
1988
+ self.fail(
1989
+ f"Only concrete class can be given where {format_type(typ, self.options)} is expected",
1990
+ context,
1991
+ code=codes.TYPE_ABSTRACT,
1992
+ )
1993
+
1994
+ def cannot_use_function_with_type(
1995
+ self, method_name: str, type_name: str, context: Context
1996
+ ) -> None:
1997
+ self.fail(f"Cannot use {method_name}() with {type_name} type", context)
1998
+
1999
+ def report_non_method_protocol(
2000
+ self, tp: TypeInfo, members: list[str], context: Context
2001
+ ) -> None:
2002
+ self.fail(
2003
+ "Only protocols that don't have non-method members can be used with issubclass()",
2004
+ context,
2005
+ )
2006
+ if len(members) < 3:
2007
+ attrs = ", ".join(members)
2008
+ self.note(f'Protocol "{tp.name}" has non-method member(s): {attrs}', context)
2009
+
2010
+ def note_call(
2011
+ self, subtype: Type, call: Type, context: Context, *, code: ErrorCode | None
2012
+ ) -> None:
2013
+ self.note(
2014
+ '"{}.__call__" has type {}'.format(
2015
+ format_type_bare(subtype, self.options),
2016
+ format_type(call, self.options, verbosity=1),
2017
+ ),
2018
+ context,
2019
+ code=code,
2020
+ )
2021
+
2022
+ def unreachable_statement(self, context: Context) -> None:
2023
+ self.fail("Statement is unreachable", context, code=codes.UNREACHABLE)
2024
+
2025
+ def redundant_left_operand(self, op_name: str, context: Context) -> None:
2026
+ """Indicates that the left operand of a boolean expression is redundant:
2027
+ it does not change the truth value of the entire condition as a whole.
2028
+ 'op_name' should either be the string "and" or the string "or".
2029
+ """
2030
+ self.redundant_expr(f'Left operand of "{op_name}"', op_name == "and", context)
2031
+
2032
+ def unreachable_right_operand(self, op_name: str, context: Context) -> None:
2033
+ """Indicates that the right operand of a boolean expression is redundant:
2034
+ it does not change the truth value of the entire condition as a whole.
2035
+ 'op_name' should either be the string "and" or the string "or".
2036
+ """
2037
+ self.fail(
2038
+ f'Right operand of "{op_name}" is never evaluated', context, code=codes.UNREACHABLE
2039
+ )
2040
+
2041
+ def redundant_condition_in_comprehension(self, truthiness: bool, context: Context) -> None:
2042
+ self.redundant_expr("If condition in comprehension", truthiness, context)
2043
+
2044
+ def redundant_condition_in_if(self, truthiness: bool, context: Context) -> None:
2045
+ self.redundant_expr("If condition", truthiness, context)
2046
+
2047
+ def redundant_expr(self, description: str, truthiness: bool, context: Context) -> None:
2048
+ self.fail(
2049
+ f"{description} is always {str(truthiness).lower()}",
2050
+ context,
2051
+ code=codes.REDUNDANT_EXPR,
2052
+ )
2053
+
2054
+ def impossible_intersection(
2055
+ self, formatted_base_class_list: str, reason: str, context: Context
2056
+ ) -> None:
2057
+ template = "Subclass of {} cannot exist: {}"
2058
+ self.fail(
2059
+ template.format(formatted_base_class_list, reason), context, code=codes.UNREACHABLE
2060
+ )
2061
+
2062
+ def report_protocol_problems(
2063
+ self,
2064
+ subtype: Instance | TupleType | TypedDictType | TypeType | CallableType,
2065
+ supertype: Instance,
2066
+ context: Context,
2067
+ *,
2068
+ code: ErrorCode | None,
2069
+ ) -> None:
2070
+ """Report possible protocol conflicts between 'subtype' and 'supertype'.
2071
+
2072
+ This includes missing members, incompatible types, and incompatible
2073
+ attribute flags, such as settable vs read-only or class variable vs
2074
+ instance variable.
2075
+ """
2076
+ OFFSET = 4 # Four spaces, so that notes will look like this:
2077
+ # note: 'Cls' is missing following 'Proto' members:
2078
+ # note: method, attr
2079
+ MAX_ITEMS = 2 # Maximum number of conflicts, missing members, and overloads shown
2080
+ # List of special situations where we don't want to report additional problems
2081
+ exclusions: dict[type, list[str]] = {
2082
+ TypedDictType: ["typing.Mapping"],
2083
+ TupleType: ["typing.Iterable", "typing.Sequence"],
2084
+ }
2085
+ if supertype.type.fullname in exclusions.get(type(subtype), []):
2086
+ return
2087
+ if any(isinstance(tp, UninhabitedType) for tp in get_proper_types(supertype.args)):
2088
+ # We don't want to add notes for failed inference (e.g. Iterable[Never]).
2089
+ # This will be only confusing a user even more.
2090
+ return
2091
+
2092
+ class_obj = False
2093
+ is_module = False
2094
+ skip = []
2095
+ if isinstance(subtype, TupleType):
2096
+ if not isinstance(subtype.partial_fallback, Instance):
2097
+ return
2098
+ subtype = subtype.partial_fallback
2099
+ elif isinstance(subtype, TypedDictType):
2100
+ if not isinstance(subtype.fallback, Instance):
2101
+ return
2102
+ subtype = subtype.fallback
2103
+ elif isinstance(subtype, TypeType):
2104
+ if not isinstance(subtype.item, Instance):
2105
+ return
2106
+ class_obj = True
2107
+ subtype = subtype.item
2108
+ elif isinstance(subtype, CallableType):
2109
+ if subtype.is_type_obj():
2110
+ ret_type = get_proper_type(subtype.ret_type)
2111
+ if isinstance(ret_type, TupleType):
2112
+ ret_type = ret_type.partial_fallback
2113
+ if not isinstance(ret_type, Instance):
2114
+ return
2115
+ class_obj = True
2116
+ subtype = ret_type
2117
+ else:
2118
+ subtype = subtype.fallback
2119
+ skip = ["__call__"]
2120
+ if subtype.extra_attrs and subtype.extra_attrs.mod_name:
2121
+ is_module = True
2122
+
2123
+ # Report missing members
2124
+ missing = get_missing_protocol_members(subtype, supertype, skip=skip)
2125
+ if (
2126
+ missing
2127
+ and (len(missing) < len(supertype.type.protocol_members) or missing == ["__call__"])
2128
+ and len(missing) <= MAX_ITEMS
2129
+ ):
2130
+ if missing == ["__call__"] and class_obj:
2131
+ self.note(
2132
+ '"{}" has constructor incompatible with "__call__" of "{}"'.format(
2133
+ subtype.type.name, supertype.type.name
2134
+ ),
2135
+ context,
2136
+ code=code,
2137
+ )
2138
+ else:
2139
+ self.note(
2140
+ '"{}" is missing following "{}" protocol member{}:'.format(
2141
+ subtype.type.name, supertype.type.name, plural_s(missing)
2142
+ ),
2143
+ context,
2144
+ code=code,
2145
+ )
2146
+ self.note(", ".join(missing), context, offset=OFFSET, code=code)
2147
+ elif len(missing) > MAX_ITEMS or len(missing) == len(supertype.type.protocol_members):
2148
+ # This is an obviously wrong type: too many missing members
2149
+ return
2150
+
2151
+ # Report member type conflicts
2152
+ conflict_types = get_conflict_protocol_types(
2153
+ subtype, supertype, class_obj=class_obj, options=self.options
2154
+ )
2155
+ if conflict_types and (
2156
+ not is_subtype(subtype, erase_type(supertype), options=self.options)
2157
+ or not subtype.type.defn.type_vars
2158
+ or not supertype.type.defn.type_vars
2159
+ # Always show detailed message for ParamSpec
2160
+ or subtype.type.has_param_spec_type
2161
+ or supertype.type.has_param_spec_type
2162
+ ):
2163
+ type_name = format_type(subtype, self.options, module_names=True)
2164
+ self.note(f"Following member(s) of {type_name} have conflicts:", context, code=code)
2165
+ for name, got, exp in conflict_types[:MAX_ITEMS]:
2166
+ exp = get_proper_type(exp)
2167
+ got = get_proper_type(got)
2168
+ if not isinstance(exp, (CallableType, Overloaded)) or not isinstance(
2169
+ got, (CallableType, Overloaded)
2170
+ ):
2171
+ self.note(
2172
+ "{}: expected {}, got {}".format(
2173
+ name, *format_type_distinctly(exp, got, options=self.options)
2174
+ ),
2175
+ context,
2176
+ offset=OFFSET,
2177
+ code=code,
2178
+ )
2179
+ else:
2180
+ self.note("Expected:", context, offset=OFFSET, code=code)
2181
+ if isinstance(exp, CallableType):
2182
+ self.note(
2183
+ pretty_callable(exp, self.options, skip_self=class_obj or is_module),
2184
+ context,
2185
+ offset=2 * OFFSET,
2186
+ code=code,
2187
+ )
2188
+ else:
2189
+ assert isinstance(exp, Overloaded)
2190
+ self.pretty_overload(
2191
+ exp, context, 2 * OFFSET, code=code, skip_self=class_obj or is_module
2192
+ )
2193
+ self.note("Got:", context, offset=OFFSET, code=code)
2194
+ if isinstance(got, CallableType):
2195
+ self.note(
2196
+ pretty_callable(got, self.options, skip_self=class_obj or is_module),
2197
+ context,
2198
+ offset=2 * OFFSET,
2199
+ code=code,
2200
+ )
2201
+ else:
2202
+ assert isinstance(got, Overloaded)
2203
+ self.pretty_overload(
2204
+ got, context, 2 * OFFSET, code=code, skip_self=class_obj or is_module
2205
+ )
2206
+ self.print_more(conflict_types, context, OFFSET, MAX_ITEMS, code=code)
2207
+
2208
+ # Report flag conflicts (i.e. settable vs read-only etc.)
2209
+ conflict_flags = get_bad_protocol_flags(subtype, supertype, class_obj=class_obj)
2210
+ for name, subflags, superflags in conflict_flags[:MAX_ITEMS]:
2211
+ if not class_obj and IS_CLASSVAR in subflags and IS_CLASSVAR not in superflags:
2212
+ self.note(
2213
+ "Protocol member {}.{} expected instance variable,"
2214
+ " got class variable".format(supertype.type.name, name),
2215
+ context,
2216
+ code=code,
2217
+ )
2218
+ if not class_obj and IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags:
2219
+ self.note(
2220
+ "Protocol member {}.{} expected class variable,"
2221
+ " got instance variable".format(supertype.type.name, name),
2222
+ context,
2223
+ code=code,
2224
+ )
2225
+ if IS_SETTABLE in superflags and IS_SETTABLE not in subflags:
2226
+ self.note(
2227
+ "Protocol member {}.{} expected settable variable,"
2228
+ " got read-only attribute".format(supertype.type.name, name),
2229
+ context,
2230
+ code=code,
2231
+ )
2232
+ if IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags:
2233
+ self.note(
2234
+ "Protocol member {}.{} expected class or static method".format(
2235
+ supertype.type.name, name
2236
+ ),
2237
+ context,
2238
+ code=code,
2239
+ )
2240
+ if (
2241
+ class_obj
2242
+ and IS_VAR in superflags
2243
+ and (IS_VAR in subflags and IS_CLASSVAR not in subflags)
2244
+ ):
2245
+ self.note(
2246
+ "Only class variables allowed for class object access on protocols,"
2247
+ ' {} is an instance variable of "{}"'.format(name, subtype.type.name),
2248
+ context,
2249
+ code=code,
2250
+ )
2251
+ if class_obj and IS_CLASSVAR in superflags:
2252
+ self.note(
2253
+ "ClassVar protocol member {}.{} can never be matched by a class object".format(
2254
+ supertype.type.name, name
2255
+ ),
2256
+ context,
2257
+ code=code,
2258
+ )
2259
+ self.print_more(conflict_flags, context, OFFSET, MAX_ITEMS, code=code)
2260
+
2261
+ def pretty_overload(
2262
+ self,
2263
+ tp: Overloaded,
2264
+ context: Context,
2265
+ offset: int,
2266
+ *,
2267
+ add_class_or_static_decorator: bool = False,
2268
+ allow_dups: bool = False,
2269
+ code: ErrorCode | None = None,
2270
+ skip_self: bool = False,
2271
+ ) -> None:
2272
+ for item in tp.items:
2273
+ self.note("@overload", context, offset=offset, allow_dups=allow_dups, code=code)
2274
+
2275
+ if add_class_or_static_decorator:
2276
+ decorator = pretty_class_or_static_decorator(item)
2277
+ if decorator is not None:
2278
+ self.note(decorator, context, offset=offset, allow_dups=allow_dups, code=code)
2279
+
2280
+ self.note(
2281
+ pretty_callable(item, self.options, skip_self=skip_self),
2282
+ context,
2283
+ offset=offset,
2284
+ allow_dups=allow_dups,
2285
+ code=code,
2286
+ )
2287
+
2288
+ def print_more(
2289
+ self,
2290
+ conflicts: Sequence[Any],
2291
+ context: Context,
2292
+ offset: int,
2293
+ max_items: int,
2294
+ *,
2295
+ code: ErrorCode | None = None,
2296
+ ) -> None:
2297
+ if len(conflicts) > max_items:
2298
+ self.note(
2299
+ f"<{len(conflicts) - max_items} more conflict(s) not shown>",
2300
+ context,
2301
+ offset=offset,
2302
+ code=code,
2303
+ )
2304
+
2305
+ def try_report_long_tuple_assignment_error(
2306
+ self,
2307
+ subtype: ProperType,
2308
+ supertype: ProperType,
2309
+ context: Context,
2310
+ msg: message_registry.ErrorMessage,
2311
+ subtype_label: str | None = None,
2312
+ supertype_label: str | None = None,
2313
+ ) -> bool:
2314
+ """Try to generate meaningful error message for very long tuple assignment
2315
+
2316
+ Returns a bool: True when generating long tuple assignment error,
2317
+ False when no such error reported
2318
+ """
2319
+ if isinstance(subtype, TupleType):
2320
+ if (
2321
+ len(subtype.items) > 10
2322
+ and isinstance(supertype, Instance)
2323
+ and supertype.type.fullname == "builtins.tuple"
2324
+ ):
2325
+ lhs_type = supertype.args[0]
2326
+ lhs_types = [lhs_type] * len(subtype.items)
2327
+ self.generate_incompatible_tuple_error(lhs_types, subtype.items, context, msg)
2328
+ return True
2329
+ elif isinstance(supertype, TupleType) and (
2330
+ len(subtype.items) > 10 or len(supertype.items) > 10
2331
+ ):
2332
+ if len(subtype.items) != len(supertype.items):
2333
+ if supertype_label is not None and subtype_label is not None:
2334
+ msg = msg.with_additional_msg(
2335
+ " ({} {}, {} {})".format(
2336
+ subtype_label,
2337
+ self.format_long_tuple_type(subtype),
2338
+ supertype_label,
2339
+ self.format_long_tuple_type(supertype),
2340
+ )
2341
+ )
2342
+ self.fail(msg.value, context, code=msg.code)
2343
+ return True
2344
+ self.generate_incompatible_tuple_error(
2345
+ supertype.items, subtype.items, context, msg
2346
+ )
2347
+ return True
2348
+ return False
2349
+
2350
+ def format_long_tuple_type(self, typ: TupleType) -> str:
2351
+ """Format very long tuple type using an ellipsis notation"""
2352
+ item_cnt = len(typ.items)
2353
+ if item_cnt > 10:
2354
+ return "{}[{}, {}, ... <{} more items>]".format(
2355
+ "tuple" if self.options.use_lowercase_names() else "Tuple",
2356
+ format_type_bare(typ.items[0], self.options),
2357
+ format_type_bare(typ.items[1], self.options),
2358
+ str(item_cnt - 2),
2359
+ )
2360
+ else:
2361
+ return format_type_bare(typ, self.options)
2362
+
2363
+ def generate_incompatible_tuple_error(
2364
+ self,
2365
+ lhs_types: list[Type],
2366
+ rhs_types: list[Type],
2367
+ context: Context,
2368
+ msg: message_registry.ErrorMessage,
2369
+ ) -> None:
2370
+ """Generate error message for individual incompatible tuple pairs"""
2371
+ error_cnt = 0
2372
+ notes: list[str] = []
2373
+ for i, (lhs_t, rhs_t) in enumerate(zip(lhs_types, rhs_types)):
2374
+ if not is_subtype(lhs_t, rhs_t):
2375
+ if error_cnt < 3:
2376
+ notes.append(
2377
+ "Expression tuple item {} has type {}; {} expected; ".format(
2378
+ str(i),
2379
+ format_type(rhs_t, self.options),
2380
+ format_type(lhs_t, self.options),
2381
+ )
2382
+ )
2383
+ error_cnt += 1
2384
+
2385
+ info = f" ({str(error_cnt)} tuple items are incompatible"
2386
+ if error_cnt - 3 > 0:
2387
+ info += f"; {str(error_cnt - 3)} items are omitted)"
2388
+ else:
2389
+ info += ")"
2390
+ msg = msg.with_additional_msg(info)
2391
+ self.fail(msg.value, context, code=msg.code)
2392
+ for note in notes:
2393
+ self.note(note, context, code=msg.code)
2394
+
2395
+ def add_fixture_note(self, fullname: str, ctx: Context) -> None:
2396
+ self.note(f'Maybe your test fixture does not define "{fullname}"?', ctx)
2397
+ if fullname in SUGGESTED_TEST_FIXTURES:
2398
+ self.note(
2399
+ "Consider adding [builtins fixtures/{}] to your test description".format(
2400
+ SUGGESTED_TEST_FIXTURES[fullname]
2401
+ ),
2402
+ ctx,
2403
+ )
2404
+
2405
+ def annotation_in_unchecked_function(self, context: Context) -> None:
2406
+ self.note(
2407
+ "By default the bodies of untyped functions are not checked,"
2408
+ " consider using --check-untyped-defs",
2409
+ context,
2410
+ code=codes.ANNOTATION_UNCHECKED,
2411
+ )
2412
+
2413
+
2414
+ def quote_type_string(type_string: str) -> str:
2415
+ """Quotes a type representation for use in messages."""
2416
+ no_quote_regex = r"^<(tuple|union): \d+ items>$"
2417
+ if (
2418
+ type_string in ["Module", "overloaded function", "Never", "<deleted>"]
2419
+ or type_string.startswith("Module ")
2420
+ or re.match(no_quote_regex, type_string) is not None
2421
+ or type_string.endswith("?")
2422
+ ):
2423
+ # Messages are easier to read if these aren't quoted. We use a
2424
+ # regex to match strings with variable contents.
2425
+ return type_string
2426
+ return f'"{type_string}"'
2427
+
2428
+
2429
+ def format_callable_args(
2430
+ arg_types: list[Type],
2431
+ arg_kinds: list[ArgKind],
2432
+ arg_names: list[str | None],
2433
+ format: Callable[[Type], str],
2434
+ verbosity: int,
2435
+ ) -> str:
2436
+ """Format a bunch of Callable arguments into a string"""
2437
+ arg_strings = []
2438
+ for arg_name, arg_type, arg_kind in zip(arg_names, arg_types, arg_kinds):
2439
+ if arg_kind == ARG_POS and arg_name is None or verbosity == 0 and arg_kind.is_positional():
2440
+ arg_strings.append(format(arg_type))
2441
+ else:
2442
+ constructor = ARG_CONSTRUCTOR_NAMES[arg_kind]
2443
+ if arg_kind.is_star() or arg_name is None:
2444
+ arg_strings.append(f"{constructor}({format(arg_type)})")
2445
+ else:
2446
+ arg_strings.append(f"{constructor}({format(arg_type)}, {repr(arg_name)})")
2447
+
2448
+ return ", ".join(arg_strings)
2449
+
2450
+
2451
+ def format_type_inner(
2452
+ typ: Type,
2453
+ verbosity: int,
2454
+ options: Options,
2455
+ fullnames: set[str] | None,
2456
+ module_names: bool = False,
2457
+ ) -> str:
2458
+ """
2459
+ Convert a type to a relatively short string suitable for error messages.
2460
+
2461
+ Args:
2462
+ verbosity: a coarse grained control on the verbosity of the type
2463
+ fullnames: a set of names that should be printed in full
2464
+ """
2465
+
2466
+ def format(typ: Type) -> str:
2467
+ return format_type_inner(typ, verbosity, options, fullnames)
2468
+
2469
+ def format_list(types: Sequence[Type]) -> str:
2470
+ return ", ".join(format(typ) for typ in types)
2471
+
2472
+ def format_union(types: Sequence[Type]) -> str:
2473
+ formatted = [format(typ) for typ in types if format(typ) != "None"]
2474
+ if any(format(typ) == "None" for typ in types):
2475
+ formatted.append("None")
2476
+ return " | ".join(formatted)
2477
+
2478
+ def format_literal_value(typ: LiteralType) -> str:
2479
+ if typ.is_enum_literal():
2480
+ underlying_type = format(typ.fallback)
2481
+ return f"{underlying_type}.{typ.value}"
2482
+ else:
2483
+ return typ.value_repr()
2484
+
2485
+ if isinstance(typ, TypeAliasType) and typ.is_recursive:
2486
+ # TODO: find balance here, str(typ) doesn't support custom verbosity, and may be
2487
+ # too verbose for user messages, OTOH it nicely shows structure of recursive types.
2488
+ if verbosity < 2:
2489
+ type_str = typ.alias.name if typ.alias else "<alias (unfixed)>"
2490
+ if typ.args:
2491
+ type_str += f"[{format_list(typ.args)}]"
2492
+ return type_str
2493
+ return str(typ)
2494
+
2495
+ # TODO: always mention type alias names in errors.
2496
+ typ = get_proper_type(typ)
2497
+
2498
+ if isinstance(typ, Instance):
2499
+ itype = typ
2500
+ # Get the short name of the type.
2501
+ if itype.type.fullname == "types.ModuleType":
2502
+ # Make some common error messages simpler and tidier.
2503
+ base_str = "Module"
2504
+ if itype.extra_attrs and itype.extra_attrs.mod_name and module_names:
2505
+ return f'{base_str} "{itype.extra_attrs.mod_name}"'
2506
+ return base_str
2507
+ if itype.type.fullname == "typing._SpecialForm":
2508
+ # This is not a real type but used for some typing-related constructs.
2509
+ return "<typing special form>"
2510
+ if itype.type.fullname in reverse_builtin_aliases and not options.use_lowercase_names():
2511
+ alias = reverse_builtin_aliases[itype.type.fullname]
2512
+ base_str = alias.split(".")[-1]
2513
+ elif verbosity >= 2 or (fullnames and itype.type.fullname in fullnames):
2514
+ base_str = itype.type.fullname
2515
+ else:
2516
+ base_str = itype.type.name
2517
+ if not itype.args:
2518
+ if itype.type.has_type_var_tuple_type and len(itype.type.type_vars) == 1:
2519
+ return base_str + "[()]"
2520
+ # No type arguments, just return the type name
2521
+ return base_str
2522
+ elif itype.type.fullname == "builtins.tuple":
2523
+ item_type_str = format(itype.args[0])
2524
+ return f"{'tuple' if options.use_lowercase_names() else 'Tuple'}[{item_type_str}, ...]"
2525
+ else:
2526
+ # There are type arguments. Convert the arguments to strings.
2527
+ return f"{base_str}[{format_list(itype.args)}]"
2528
+ elif isinstance(typ, UnpackType):
2529
+ if options.use_star_unpack():
2530
+ return f"*{format(typ.type)}"
2531
+ return f"Unpack[{format(typ.type)}]"
2532
+ elif isinstance(typ, TypeVarType):
2533
+ # This is similar to non-generic instance types.
2534
+ return typ.name
2535
+ elif isinstance(typ, TypeVarTupleType):
2536
+ # This is similar to non-generic instance types.
2537
+ return typ.name
2538
+ elif isinstance(typ, ParamSpecType):
2539
+ # Concatenate[..., P]
2540
+ if typ.prefix.arg_types:
2541
+ args = format_callable_args(
2542
+ typ.prefix.arg_types, typ.prefix.arg_kinds, typ.prefix.arg_names, format, verbosity
2543
+ )
2544
+
2545
+ return f"[{args}, **{typ.name_with_suffix()}]"
2546
+ else:
2547
+ return typ.name_with_suffix()
2548
+ elif isinstance(typ, TupleType):
2549
+ # Prefer the name of the fallback class (if not tuple), as it's more informative.
2550
+ if typ.partial_fallback.type.fullname != "builtins.tuple":
2551
+ return format(typ.partial_fallback)
2552
+ type_items = format_list(typ.items) or "()"
2553
+ if options.use_lowercase_names():
2554
+ s = f"tuple[{type_items}]"
2555
+ else:
2556
+ s = f"Tuple[{type_items}]"
2557
+ return s
2558
+ elif isinstance(typ, TypedDictType):
2559
+ # If the TypedDictType is named, return the name
2560
+ if not typ.is_anonymous():
2561
+ return format(typ.fallback)
2562
+ items = []
2563
+ for item_name, item_type in typ.items.items():
2564
+ modifier = "" if item_name in typ.required_keys else "?"
2565
+ items.append(f"{item_name!r}{modifier}: {format(item_type)}")
2566
+ s = f"TypedDict({{{', '.join(items)}}})"
2567
+ return s
2568
+ elif isinstance(typ, LiteralType):
2569
+ return f"Literal[{format_literal_value(typ)}]"
2570
+ elif isinstance(typ, UnionType):
2571
+ literal_items, union_items = separate_union_literals(typ)
2572
+
2573
+ # Coalesce multiple Literal[] members. This also changes output order.
2574
+ # If there's just one Literal item, retain the original ordering.
2575
+ if len(literal_items) > 1:
2576
+ literal_str = "Literal[{}]".format(
2577
+ ", ".join(format_literal_value(t) for t in literal_items)
2578
+ )
2579
+
2580
+ if len(union_items) == 1 and isinstance(get_proper_type(union_items[0]), NoneType):
2581
+ return (
2582
+ f"{literal_str} | None"
2583
+ if options.use_or_syntax()
2584
+ else f"Optional[{literal_str}]"
2585
+ )
2586
+ elif union_items:
2587
+ return (
2588
+ f"{literal_str} | {format_union(union_items)}"
2589
+ if options.use_or_syntax()
2590
+ else f"Union[{format_list(union_items)}, {literal_str}]"
2591
+ )
2592
+ else:
2593
+ return literal_str
2594
+ else:
2595
+ # Only print Union as Optional if the Optional wouldn't have to contain another Union
2596
+ print_as_optional = (
2597
+ len(typ.items) - sum(isinstance(get_proper_type(t), NoneType) for t in typ.items)
2598
+ == 1
2599
+ )
2600
+ if print_as_optional:
2601
+ rest = [t for t in typ.items if not isinstance(get_proper_type(t), NoneType)]
2602
+ return (
2603
+ f"{format(rest[0])} | None"
2604
+ if options.use_or_syntax()
2605
+ else f"Optional[{format(rest[0])}]"
2606
+ )
2607
+ else:
2608
+ s = (
2609
+ format_union(typ.items)
2610
+ if options.use_or_syntax()
2611
+ else f"Union[{format_list(typ.items)}]"
2612
+ )
2613
+ return s
2614
+ elif isinstance(typ, NoneType):
2615
+ return "None"
2616
+ elif isinstance(typ, AnyType):
2617
+ return "Any"
2618
+ elif isinstance(typ, DeletedType):
2619
+ return "<deleted>"
2620
+ elif isinstance(typ, UninhabitedType):
2621
+ if typ.is_noreturn:
2622
+ return "NoReturn"
2623
+ else:
2624
+ return "Never"
2625
+ elif isinstance(typ, TypeType):
2626
+ type_name = "type" if options.use_lowercase_names() else "Type"
2627
+ return f"{type_name}[{format(typ.item)}]"
2628
+ elif isinstance(typ, FunctionLike):
2629
+ func = typ
2630
+ if func.is_type_obj():
2631
+ # The type of a type object type can be derived from the
2632
+ # return type (this always works).
2633
+ return format(TypeType.make_normalized(erase_type(func.items[0].ret_type)))
2634
+ elif isinstance(func, CallableType):
2635
+ if func.type_guard is not None:
2636
+ return_type = f"TypeGuard[{format(func.type_guard)}]"
2637
+ else:
2638
+ return_type = format(func.ret_type)
2639
+ if func.is_ellipsis_args:
2640
+ return f"Callable[..., {return_type}]"
2641
+ param_spec = func.param_spec()
2642
+ if param_spec is not None:
2643
+ return f"Callable[{format(param_spec)}, {return_type}]"
2644
+ args = format_callable_args(
2645
+ func.arg_types, func.arg_kinds, func.arg_names, format, verbosity
2646
+ )
2647
+ return f"Callable[[{args}], {return_type}]"
2648
+ else:
2649
+ # Use a simple representation for function types; proper
2650
+ # function types may result in long and difficult-to-read
2651
+ # error messages.
2652
+ return "overloaded function"
2653
+ elif isinstance(typ, UnboundType):
2654
+ return typ.accept(TypeStrVisitor(options=options))
2655
+ elif isinstance(typ, Parameters):
2656
+ args = format_callable_args(typ.arg_types, typ.arg_kinds, typ.arg_names, format, verbosity)
2657
+ return f"[{args}]"
2658
+ elif typ is None:
2659
+ raise RuntimeError("Type is None")
2660
+ else:
2661
+ # Default case; we simply have to return something meaningful here.
2662
+ return "object"
2663
+
2664
+
2665
+ def collect_all_instances(t: Type) -> list[Instance]:
2666
+ """Return all instances that `t` contains (including `t`).
2667
+
2668
+ This is similar to collect_all_inner_types from typeanal but only
2669
+ returns instances and will recurse into fallbacks.
2670
+ """
2671
+ visitor = CollectAllInstancesQuery()
2672
+ t.accept(visitor)
2673
+ return visitor.instances
2674
+
2675
+
2676
+ class CollectAllInstancesQuery(TypeTraverserVisitor):
2677
+ def __init__(self) -> None:
2678
+ self.instances: list[Instance] = []
2679
+
2680
+ def visit_instance(self, t: Instance) -> None:
2681
+ self.instances.append(t)
2682
+ super().visit_instance(t)
2683
+
2684
+ def visit_type_alias_type(self, t: TypeAliasType) -> None:
2685
+ if t.alias and not t.is_recursive:
2686
+ t.alias.target.accept(self)
2687
+ super().visit_type_alias_type(t)
2688
+
2689
+
2690
+ def find_type_overlaps(*types: Type) -> set[str]:
2691
+ """Return a set of fullnames that share a short name and appear in either type.
2692
+
2693
+ This is used to ensure that distinct types with the same short name are printed
2694
+ with their fullname.
2695
+ """
2696
+ d: dict[str, set[str]] = {}
2697
+ for type in types:
2698
+ for inst in collect_all_instances(type):
2699
+ d.setdefault(inst.type.name, set()).add(inst.type.fullname)
2700
+ for shortname in d.keys():
2701
+ if f"typing.{shortname}" in TYPES_FOR_UNIMPORTED_HINTS:
2702
+ d[shortname].add(f"typing.{shortname}")
2703
+
2704
+ overlaps: set[str] = set()
2705
+ for fullnames in d.values():
2706
+ if len(fullnames) > 1:
2707
+ overlaps.update(fullnames)
2708
+ return overlaps
2709
+
2710
+
2711
+ def format_type(
2712
+ typ: Type, options: Options, verbosity: int = 0, module_names: bool = False
2713
+ ) -> str:
2714
+ """
2715
+ Convert a type to a relatively short string suitable for error messages.
2716
+
2717
+ `verbosity` is a coarse grained control on the verbosity of the type
2718
+
2719
+ This function returns a string appropriate for unmodified use in error
2720
+ messages; this means that it will be quoted in most cases. If
2721
+ modification of the formatted string is required, callers should use
2722
+ format_type_bare.
2723
+ """
2724
+ return quote_type_string(format_type_bare(typ, options, verbosity, module_names))
2725
+
2726
+
2727
+ def format_type_bare(
2728
+ typ: Type, options: Options, verbosity: int = 0, module_names: bool = False
2729
+ ) -> str:
2730
+ """
2731
+ Convert a type to a relatively short string suitable for error messages.
2732
+
2733
+ `verbosity` is a coarse grained control on the verbosity of the type
2734
+ `fullnames` specifies a set of names that should be printed in full
2735
+
2736
+ This function will return an unquoted string. If a caller doesn't need to
2737
+ perform post-processing on the string output, format_type should be used
2738
+ instead. (The caller may want to use quote_type_string after
2739
+ processing has happened, to maintain consistent quoting in messages.)
2740
+ """
2741
+ return format_type_inner(typ, verbosity, options, find_type_overlaps(typ), module_names)
2742
+
2743
+
2744
+ def format_type_distinctly(*types: Type, options: Options, bare: bool = False) -> tuple[str, ...]:
2745
+ """Jointly format types to distinct strings.
2746
+
2747
+ Increase the verbosity of the type strings until they become distinct
2748
+ while also requiring that distinct types with the same short name are
2749
+ formatted distinctly.
2750
+
2751
+ By default, the returned strings are created using format_type() and will be
2752
+ quoted accordingly. If ``bare`` is True, the returned strings will not
2753
+ be quoted; callers who need to do post-processing of the strings before
2754
+ quoting them (such as prepending * or **) should use this.
2755
+ """
2756
+ overlapping = find_type_overlaps(*types)
2757
+ for verbosity in range(2):
2758
+ strs = [
2759
+ format_type_inner(type, verbosity=verbosity, options=options, fullnames=overlapping)
2760
+ for type in types
2761
+ ]
2762
+ if len(set(strs)) == len(strs):
2763
+ break
2764
+ if bare:
2765
+ return tuple(strs)
2766
+ else:
2767
+ return tuple(quote_type_string(s) for s in strs)
2768
+
2769
+
2770
+ def pretty_class_or_static_decorator(tp: CallableType) -> str | None:
2771
+ """Return @classmethod or @staticmethod, if any, for the given callable type."""
2772
+ if tp.definition is not None and isinstance(tp.definition, SYMBOL_FUNCBASE_TYPES):
2773
+ if tp.definition.is_class:
2774
+ return "@classmethod"
2775
+ if tp.definition.is_static:
2776
+ return "@staticmethod"
2777
+ return None
2778
+
2779
+
2780
+ def pretty_callable(tp: CallableType, options: Options, skip_self: bool = False) -> str:
2781
+ """Return a nice easily-readable representation of a callable type.
2782
+ For example:
2783
+ def [T <: int] f(self, x: int, y: T) -> None
2784
+
2785
+ If skip_self is True, print an actual callable type, as it would appear
2786
+ when bound on an instance/class, rather than how it would appear in the
2787
+ defining statement.
2788
+ """
2789
+ s = ""
2790
+ asterisk = False
2791
+ slash = False
2792
+ for i in range(len(tp.arg_types)):
2793
+ if s:
2794
+ s += ", "
2795
+ if tp.arg_kinds[i].is_named() and not asterisk:
2796
+ s += "*, "
2797
+ asterisk = True
2798
+ if tp.arg_kinds[i] == ARG_STAR:
2799
+ s += "*"
2800
+ asterisk = True
2801
+ if tp.arg_kinds[i] == ARG_STAR2:
2802
+ s += "**"
2803
+ name = tp.arg_names[i]
2804
+ if name:
2805
+ s += name + ": "
2806
+ type_str = format_type_bare(tp.arg_types[i], options)
2807
+ if tp.arg_kinds[i] == ARG_STAR2 and tp.unpack_kwargs:
2808
+ type_str = f"Unpack[{type_str}]"
2809
+ s += type_str
2810
+ if tp.arg_kinds[i].is_optional():
2811
+ s += " = ..."
2812
+ if (
2813
+ not slash
2814
+ and tp.arg_kinds[i].is_positional()
2815
+ and name is None
2816
+ and (
2817
+ i == len(tp.arg_types) - 1
2818
+ or (tp.arg_names[i + 1] is not None or not tp.arg_kinds[i + 1].is_positional())
2819
+ )
2820
+ ):
2821
+ s += ", /"
2822
+ slash = True
2823
+
2824
+ # If we got a "special arg" (i.e: self, cls, etc...), prepend it to the arg list
2825
+ if (
2826
+ isinstance(tp.definition, FuncDef)
2827
+ and hasattr(tp.definition, "arguments")
2828
+ and not tp.from_concatenate
2829
+ ):
2830
+ definition_arg_names = [arg.variable.name for arg in tp.definition.arguments]
2831
+ if (
2832
+ len(definition_arg_names) > len(tp.arg_names)
2833
+ and definition_arg_names[0]
2834
+ and not skip_self
2835
+ ):
2836
+ if s:
2837
+ s = ", " + s
2838
+ s = definition_arg_names[0] + s
2839
+ s = f"{tp.definition.name}({s})"
2840
+ elif tp.name:
2841
+ first_arg = tp.def_extras.get("first_arg")
2842
+ if first_arg:
2843
+ if s:
2844
+ s = ", " + s
2845
+ s = first_arg + s
2846
+ s = f"{tp.name.split()[0]}({s})" # skip "of Class" part
2847
+ else:
2848
+ s = f"({s})"
2849
+
2850
+ s += " -> "
2851
+ if tp.type_guard is not None:
2852
+ s += f"TypeGuard[{format_type_bare(tp.type_guard, options)}]"
2853
+ else:
2854
+ s += format_type_bare(tp.ret_type, options)
2855
+
2856
+ if tp.variables:
2857
+ tvars = []
2858
+ for tvar in tp.variables:
2859
+ if isinstance(tvar, TypeVarType):
2860
+ upper_bound = get_proper_type(tvar.upper_bound)
2861
+ if (
2862
+ isinstance(upper_bound, Instance)
2863
+ and upper_bound.type.fullname != "builtins.object"
2864
+ ):
2865
+ tvars.append(f"{tvar.name} <: {format_type_bare(upper_bound, options)}")
2866
+ elif tvar.values:
2867
+ tvars.append(
2868
+ "{} in ({})".format(
2869
+ tvar.name,
2870
+ ", ".join([format_type_bare(tp, options) for tp in tvar.values]),
2871
+ )
2872
+ )
2873
+ else:
2874
+ tvars.append(tvar.name)
2875
+ else:
2876
+ # For other TypeVarLikeTypes, just use the repr
2877
+ tvars.append(repr(tvar))
2878
+ s = f"[{', '.join(tvars)}] {s}"
2879
+ return f"def {s}"
2880
+
2881
+
2882
+ def variance_string(variance: int) -> str:
2883
+ if variance == COVARIANT:
2884
+ return "covariant"
2885
+ elif variance == CONTRAVARIANT:
2886
+ return "contravariant"
2887
+ else:
2888
+ return "invariant"
2889
+
2890
+
2891
+ def get_missing_protocol_members(left: Instance, right: Instance, skip: list[str]) -> list[str]:
2892
+ """Find all protocol members of 'right' that are not implemented
2893
+ (i.e. completely missing) in 'left'.
2894
+ """
2895
+ assert right.type.is_protocol
2896
+ missing: list[str] = []
2897
+ for member in right.type.protocol_members:
2898
+ if member in skip:
2899
+ continue
2900
+ if not find_member(member, left, left):
2901
+ missing.append(member)
2902
+ return missing
2903
+
2904
+
2905
+ def get_conflict_protocol_types(
2906
+ left: Instance, right: Instance, class_obj: bool = False, options: Options | None = None
2907
+ ) -> list[tuple[str, Type, Type]]:
2908
+ """Find members that are defined in 'left' but have incompatible types.
2909
+ Return them as a list of ('member', 'got', 'expected').
2910
+ """
2911
+ assert right.type.is_protocol
2912
+ conflicts: list[tuple[str, Type, Type]] = []
2913
+ for member in right.type.protocol_members:
2914
+ if member in ("__init__", "__new__"):
2915
+ continue
2916
+ supertype = find_member(member, right, left)
2917
+ assert supertype is not None
2918
+ subtype = mypy.typeops.get_protocol_member(left, member, class_obj)
2919
+ if not subtype:
2920
+ continue
2921
+ is_compat = is_subtype(subtype, supertype, ignore_pos_arg_names=True, options=options)
2922
+ if IS_SETTABLE in get_member_flags(member, right):
2923
+ is_compat = is_compat and is_subtype(supertype, subtype, options=options)
2924
+ if not is_compat:
2925
+ conflicts.append((member, subtype, supertype))
2926
+ return conflicts
2927
+
2928
+
2929
+ def get_bad_protocol_flags(
2930
+ left: Instance, right: Instance, class_obj: bool = False
2931
+ ) -> list[tuple[str, set[int], set[int]]]:
2932
+ """Return all incompatible attribute flags for members that are present in both
2933
+ 'left' and 'right'.
2934
+ """
2935
+ assert right.type.is_protocol
2936
+ all_flags: list[tuple[str, set[int], set[int]]] = []
2937
+ for member in right.type.protocol_members:
2938
+ if find_member(member, left, left):
2939
+ item = (member, get_member_flags(member, left), get_member_flags(member, right))
2940
+ all_flags.append(item)
2941
+ bad_flags = []
2942
+ for name, subflags, superflags in all_flags:
2943
+ if (
2944
+ IS_CLASSVAR in subflags
2945
+ and IS_CLASSVAR not in superflags
2946
+ and IS_SETTABLE in superflags
2947
+ or IS_CLASSVAR in superflags
2948
+ and IS_CLASSVAR not in subflags
2949
+ or IS_SETTABLE in superflags
2950
+ and IS_SETTABLE not in subflags
2951
+ or IS_CLASS_OR_STATIC in superflags
2952
+ and IS_CLASS_OR_STATIC not in subflags
2953
+ or class_obj
2954
+ and IS_VAR in superflags
2955
+ and IS_CLASSVAR not in subflags
2956
+ or class_obj
2957
+ and IS_CLASSVAR in superflags
2958
+ ):
2959
+ bad_flags.append((name, subflags, superflags))
2960
+ return bad_flags
2961
+
2962
+
2963
+ def capitalize(s: str) -> str:
2964
+ """Capitalize the first character of a string."""
2965
+ if s == "":
2966
+ return ""
2967
+ else:
2968
+ return s[0].upper() + s[1:]
2969
+
2970
+
2971
+ def extract_type(name: str) -> str:
2972
+ """If the argument is the name of a method (of form C.m), return
2973
+ the type portion in quotes (e.g. "y"). Otherwise, return the string
2974
+ unmodified.
2975
+ """
2976
+ name = re.sub('^"[a-zA-Z0-9_]+" of ', "", name)
2977
+ return name
2978
+
2979
+
2980
+ def strip_quotes(s: str) -> str:
2981
+ """Strip a double quote at the beginning and end of the string, if any."""
2982
+ s = re.sub('^"', "", s)
2983
+ s = re.sub('"$', "", s)
2984
+ return s
2985
+
2986
+
2987
+ def format_string_list(lst: list[str]) -> str:
2988
+ assert lst
2989
+ if len(lst) == 1:
2990
+ return lst[0]
2991
+ elif len(lst) <= 5:
2992
+ return f"{', '.join(lst[:-1])} and {lst[-1]}"
2993
+ else:
2994
+ return "%s, ... and %s (%i methods suppressed)" % (
2995
+ ", ".join(lst[:2]),
2996
+ lst[-1],
2997
+ len(lst) - 3,
2998
+ )
2999
+
3000
+
3001
+ def format_item_name_list(s: Iterable[str]) -> str:
3002
+ lst = list(s)
3003
+ if len(lst) <= 5:
3004
+ return "(" + ", ".join([f'"{name}"' for name in lst]) + ")"
3005
+ else:
3006
+ return "(" + ", ".join([f'"{name}"' for name in lst[:5]]) + ", ...)"
3007
+
3008
+
3009
+ def callable_name(type: FunctionLike) -> str | None:
3010
+ name = type.get_name()
3011
+ if name is not None and name[0] != "<":
3012
+ return f'"{name}"'.replace(" of ", '" of "')
3013
+ return name
3014
+
3015
+
3016
+ def for_function(callee: CallableType) -> str:
3017
+ name = callable_name(callee)
3018
+ if name is not None:
3019
+ return f" for {name}"
3020
+ return ""
3021
+
3022
+
3023
+ def wrong_type_arg_count(low: int, high: int, act: str, name: str) -> str:
3024
+ if low == high:
3025
+ s = f"{low} type arguments"
3026
+ if low == 0:
3027
+ s = "no type arguments"
3028
+ elif low == 1:
3029
+ s = "1 type argument"
3030
+ else:
3031
+ s = f"between {low} and {high} type arguments"
3032
+ if act == "0":
3033
+ act = "none"
3034
+ return f'"{name}" expects {s}, but {act} given'
3035
+
3036
+
3037
+ def find_defining_module(modules: dict[str, MypyFile], typ: CallableType) -> MypyFile | None:
3038
+ if not typ.definition:
3039
+ return None
3040
+ fullname = typ.definition.fullname
3041
+ if "." in fullname:
3042
+ for i in range(fullname.count(".")):
3043
+ module_name = fullname.rsplit(".", i + 1)[0]
3044
+ try:
3045
+ return modules[module_name]
3046
+ except KeyError:
3047
+ pass
3048
+ assert False, "Couldn't determine module from CallableType"
3049
+ return None
3050
+
3051
+
3052
+ # For hard-coding suggested missing member alternatives.
3053
+ COMMON_MISTAKES: Final[dict[str, Sequence[str]]] = {"add": ("append", "extend")}
3054
+
3055
+
3056
+ def _real_quick_ratio(a: str, b: str) -> float:
3057
+ # this is an upper bound on difflib.SequenceMatcher.ratio
3058
+ # similar to difflib.SequenceMatcher.real_quick_ratio, but faster since we don't instantiate
3059
+ al = len(a)
3060
+ bl = len(b)
3061
+ return 2.0 * min(al, bl) / (al + bl)
3062
+
3063
+
3064
+ def best_matches(current: str, options: Collection[str], n: int) -> list[str]:
3065
+ if not current:
3066
+ return []
3067
+ # narrow down options cheaply
3068
+ options = [o for o in options if _real_quick_ratio(current, o) > 0.75]
3069
+ if len(options) >= 50:
3070
+ options = [o for o in options if abs(len(o) - len(current)) <= 1]
3071
+
3072
+ ratios = {option: difflib.SequenceMatcher(a=current, b=option).ratio() for option in options}
3073
+ options = [option for option, ratio in ratios.items() if ratio > 0.75]
3074
+ return sorted(options, key=lambda v: (-ratios[v], v))[:n]
3075
+
3076
+
3077
+ def pretty_seq(args: Sequence[str], conjunction: str) -> str:
3078
+ quoted = ['"' + a + '"' for a in args]
3079
+ if len(quoted) == 1:
3080
+ return quoted[0]
3081
+ if len(quoted) == 2:
3082
+ return f"{quoted[0]} {conjunction} {quoted[1]}"
3083
+ last_sep = ", " + conjunction + " "
3084
+ return ", ".join(quoted[:-1]) + last_sep + quoted[-1]
3085
+
3086
+
3087
+ def append_invariance_notes(
3088
+ notes: list[str], arg_type: Instance, expected_type: Instance
3089
+ ) -> list[str]:
3090
+ """Explain that the type is invariant and give notes for how to solve the issue."""
3091
+ invariant_type = ""
3092
+ covariant_suggestion = ""
3093
+ if (
3094
+ arg_type.type.fullname == "builtins.list"
3095
+ and expected_type.type.fullname == "builtins.list"
3096
+ and is_subtype(arg_type.args[0], expected_type.args[0])
3097
+ ):
3098
+ invariant_type = "List"
3099
+ covariant_suggestion = 'Consider using "Sequence" instead, which is covariant'
3100
+ elif (
3101
+ arg_type.type.fullname == "builtins.dict"
3102
+ and expected_type.type.fullname == "builtins.dict"
3103
+ and is_same_type(arg_type.args[0], expected_type.args[0])
3104
+ and is_subtype(arg_type.args[1], expected_type.args[1])
3105
+ ):
3106
+ invariant_type = "Dict"
3107
+ covariant_suggestion = (
3108
+ 'Consider using "Mapping" instead, which is covariant in the value type'
3109
+ )
3110
+ if invariant_type and covariant_suggestion:
3111
+ notes.append(
3112
+ f'"{invariant_type}" is invariant -- see '
3113
+ + "https://mypy.readthedocs.io/en/stable/common_issues.html#variance"
3114
+ )
3115
+ notes.append(covariant_suggestion)
3116
+ return notes
3117
+
3118
+
3119
+ def append_numbers_notes(
3120
+ notes: list[str], arg_type: Instance, expected_type: Instance
3121
+ ) -> list[str]:
3122
+ """Explain if an unsupported type from "numbers" is used in a subtype check."""
3123
+ if expected_type.type.fullname in UNSUPPORTED_NUMBERS_TYPES:
3124
+ notes.append('Types from "numbers" aren\'t supported for static type checking')
3125
+ notes.append("See https://peps.python.org/pep-0484/#the-numeric-tower")
3126
+ notes.append("Consider using a protocol instead, such as typing.SupportsFloat")
3127
+ return notes
3128
+
3129
+
3130
+ def make_inferred_type_note(
3131
+ context: Context, subtype: Type, supertype: Type, supertype_str: str
3132
+ ) -> str:
3133
+ """Explain that the user may have forgotten to type a variable.
3134
+
3135
+ The user does not expect an error if the inferred container type is the same as the return
3136
+ type of a function and the argument type(s) are a subtype of the argument type(s) of the
3137
+ return type. This note suggests that they add a type annotation with the return type instead
3138
+ of relying on the inferred type.
3139
+ """
3140
+ subtype = get_proper_type(subtype)
3141
+ supertype = get_proper_type(supertype)
3142
+ if (
3143
+ isinstance(subtype, Instance)
3144
+ and isinstance(supertype, Instance)
3145
+ and subtype.type.fullname == supertype.type.fullname
3146
+ and subtype.args
3147
+ and supertype.args
3148
+ and isinstance(context, ReturnStmt)
3149
+ and isinstance(context.expr, NameExpr)
3150
+ and isinstance(context.expr.node, Var)
3151
+ and context.expr.node.is_inferred
3152
+ ):
3153
+ for subtype_arg, supertype_arg in zip(subtype.args, supertype.args):
3154
+ if not is_subtype(subtype_arg, supertype_arg):
3155
+ return ""
3156
+ var_name = context.expr.name
3157
+ return 'Perhaps you need a type annotation for "{}"? Suggestion: {}'.format(
3158
+ var_name, supertype_str
3159
+ )
3160
+ return ""
3161
+
3162
+
3163
+ def format_key_list(keys: list[str], *, short: bool = False) -> str:
3164
+ formatted_keys = [f'"{key}"' for key in keys]
3165
+ td = "" if short else "TypedDict "
3166
+ if len(keys) == 0:
3167
+ return f"no {td}keys"
3168
+ elif len(keys) == 1:
3169
+ return f"{td}key {formatted_keys[0]}"
3170
+ else:
3171
+ return f"{td}keys ({', '.join(formatted_keys)})"