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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (759) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +5 -0
  3. package/package.json +23 -0
  4. package/python/DLLs/_asyncio.pyd +0 -0
  5. package/python/DLLs/_bz2.pyd +0 -0
  6. package/python/DLLs/_ctypes.pyd +0 -0
  7. package/python/DLLs/_ctypes_test.pyd +0 -0
  8. package/python/DLLs/_decimal.pyd +0 -0
  9. package/python/DLLs/_elementtree.pyd +0 -0
  10. package/python/DLLs/_hashlib.pyd +0 -0
  11. package/python/DLLs/_lzma.pyd +0 -0
  12. package/python/DLLs/_multiprocessing.pyd +0 -0
  13. package/python/DLLs/_overlapped.pyd +0 -0
  14. package/python/DLLs/_queue.pyd +0 -0
  15. package/python/DLLs/_socket.pyd +0 -0
  16. package/python/DLLs/_sqlite3.pyd +0 -0
  17. package/python/DLLs/_ssl.pyd +0 -0
  18. package/python/DLLs/_testbuffer.pyd +0 -0
  19. package/python/DLLs/_testcapi.pyd +0 -0
  20. package/python/DLLs/_testclinic.pyd +0 -0
  21. package/python/DLLs/_testclinic_limited.pyd +0 -0
  22. package/python/DLLs/_testconsole.pyd +0 -0
  23. package/python/DLLs/_testimportmultiple.pyd +0 -0
  24. package/python/DLLs/_testinternalcapi.pyd +0 -0
  25. package/python/DLLs/_testlimitedcapi.pyd +0 -0
  26. package/python/DLLs/_testmultiphase.pyd +0 -0
  27. package/python/DLLs/_testsinglephase.pyd +0 -0
  28. package/python/DLLs/_uuid.pyd +0 -0
  29. package/python/DLLs/_wmi.pyd +0 -0
  30. package/python/DLLs/_zoneinfo.pyd +0 -0
  31. package/python/DLLs/libcrypto-3-x64.dll +0 -0
  32. package/python/DLLs/libffi-8.dll +0 -0
  33. package/python/DLLs/libssl-3-x64.dll +0 -0
  34. package/python/DLLs/pyexpat.pyd +0 -0
  35. package/python/DLLs/select.pyd +0 -0
  36. package/python/DLLs/sqlite3.dll +0 -0
  37. package/python/DLLs/unicodedata.pyd +0 -0
  38. package/python/DLLs/winsound.pyd +0 -0
  39. package/python/DLLs/zlib1.dll +0 -0
  40. package/python/LICENSE.txt +445 -0
  41. package/python/Lib/__future__.py +147 -0
  42. package/python/Lib/__hello__.py +16 -0
  43. package/python/Lib/__pycache__/__future__.cpython-313.pyc +0 -0
  44. package/python/Lib/__pycache__/_colorize.cpython-313.pyc +0 -0
  45. package/python/Lib/__pycache__/_compat_pickle.cpython-313.pyc +0 -0
  46. package/python/Lib/__pycache__/_compression.cpython-313.pyc +0 -0
  47. package/python/Lib/__pycache__/_markupbase.cpython-313.pyc +0 -0
  48. package/python/Lib/__pycache__/_opcode_metadata.cpython-313.pyc +0 -0
  49. package/python/Lib/__pycache__/_weakrefset.cpython-313.pyc +0 -0
  50. package/python/Lib/__pycache__/ast.cpython-313.pyc +0 -0
  51. package/python/Lib/__pycache__/base64.cpython-313.pyc +0 -0
  52. package/python/Lib/__pycache__/bisect.cpython-313.pyc +0 -0
  53. package/python/Lib/__pycache__/bz2.cpython-313.pyc +0 -0
  54. package/python/Lib/__pycache__/calendar.cpython-313.pyc +0 -0
  55. package/python/Lib/__pycache__/colorsys.cpython-313.pyc +0 -0
  56. package/python/Lib/__pycache__/compileall.cpython-313.pyc +0 -0
  57. package/python/Lib/__pycache__/configparser.cpython-313.pyc +0 -0
  58. package/python/Lib/__pycache__/contextlib.cpython-313.pyc +0 -0
  59. package/python/Lib/__pycache__/copy.cpython-313.pyc +0 -0
  60. package/python/Lib/__pycache__/copyreg.cpython-313.pyc +0 -0
  61. package/python/Lib/__pycache__/csv.cpython-313.pyc +0 -0
  62. package/python/Lib/__pycache__/dataclasses.cpython-313.pyc +0 -0
  63. package/python/Lib/__pycache__/datetime.cpython-313.pyc +0 -0
  64. package/python/Lib/__pycache__/decimal.cpython-313.pyc +0 -0
  65. package/python/Lib/__pycache__/dis.cpython-313.pyc +0 -0
  66. package/python/Lib/__pycache__/enum.cpython-313.pyc +0 -0
  67. package/python/Lib/__pycache__/filecmp.cpython-313.pyc +0 -0
  68. package/python/Lib/__pycache__/fnmatch.cpython-313.pyc +0 -0
  69. package/python/Lib/__pycache__/fractions.cpython-313.pyc +0 -0
  70. package/python/Lib/__pycache__/functools.cpython-313.pyc +0 -0
  71. package/python/Lib/__pycache__/getpass.cpython-313.pyc +0 -0
  72. package/python/Lib/__pycache__/gettext.cpython-313.pyc +0 -0
  73. package/python/Lib/__pycache__/glob.cpython-313.pyc +0 -0
  74. package/python/Lib/__pycache__/gzip.cpython-313.pyc +0 -0
  75. package/python/Lib/__pycache__/hashlib.cpython-313.pyc +0 -0
  76. package/python/Lib/__pycache__/heapq.cpython-313.pyc +0 -0
  77. package/python/Lib/__pycache__/hmac.cpython-313.pyc +0 -0
  78. package/python/Lib/__pycache__/inspect.cpython-313.pyc +0 -0
  79. package/python/Lib/__pycache__/ipaddress.cpython-313.pyc +0 -0
  80. package/python/Lib/__pycache__/keyword.cpython-313.pyc +0 -0
  81. package/python/Lib/__pycache__/linecache.cpython-313.pyc +0 -0
  82. package/python/Lib/__pycache__/locale.cpython-313.pyc +0 -0
  83. package/python/Lib/__pycache__/lzma.cpython-313.pyc +0 -0
  84. package/python/Lib/__pycache__/mimetypes.cpython-313.pyc +0 -0
  85. package/python/Lib/__pycache__/nturl2path.cpython-313.pyc +0 -0
  86. package/python/Lib/__pycache__/numbers.cpython-313.pyc +0 -0
  87. package/python/Lib/__pycache__/opcode.cpython-313.pyc +0 -0
  88. package/python/Lib/__pycache__/operator.cpython-313.pyc +0 -0
  89. package/python/Lib/__pycache__/optparse.cpython-313.pyc +0 -0
  90. package/python/Lib/__pycache__/pickle.cpython-313.pyc +0 -0
  91. package/python/Lib/__pycache__/pkgutil.cpython-313.pyc +0 -0
  92. package/python/Lib/__pycache__/platform.cpython-313.pyc +0 -0
  93. package/python/Lib/__pycache__/py_compile.cpython-313.pyc +0 -0
  94. package/python/Lib/__pycache__/queue.cpython-313.pyc +0 -0
  95. package/python/Lib/__pycache__/quopri.cpython-313.pyc +0 -0
  96. package/python/Lib/__pycache__/random.cpython-313.pyc +0 -0
  97. package/python/Lib/__pycache__/reprlib.cpython-313.pyc +0 -0
  98. package/python/Lib/__pycache__/selectors.cpython-313.pyc +0 -0
  99. package/python/Lib/__pycache__/shlex.cpython-313.pyc +0 -0
  100. package/python/Lib/__pycache__/shutil.cpython-313.pyc +0 -0
  101. package/python/Lib/__pycache__/signal.cpython-313.pyc +0 -0
  102. package/python/Lib/__pycache__/socket.cpython-313.pyc +0 -0
  103. package/python/Lib/__pycache__/socketserver.cpython-313.pyc +0 -0
  104. package/python/Lib/__pycache__/ssl.cpython-313.pyc +0 -0
  105. package/python/Lib/__pycache__/string.cpython-313.pyc +0 -0
  106. package/python/Lib/__pycache__/stringprep.cpython-313.pyc +0 -0
  107. package/python/Lib/__pycache__/struct.cpython-313.pyc +0 -0
  108. package/python/Lib/__pycache__/subprocess.cpython-313.pyc +0 -0
  109. package/python/Lib/__pycache__/tarfile.cpython-313.pyc +0 -0
  110. package/python/Lib/__pycache__/tempfile.cpython-313.pyc +0 -0
  111. package/python/Lib/__pycache__/textwrap.cpython-313.pyc +0 -0
  112. package/python/Lib/__pycache__/threading.cpython-313.pyc +0 -0
  113. package/python/Lib/__pycache__/token.cpython-313.pyc +0 -0
  114. package/python/Lib/__pycache__/tokenize.cpython-313.pyc +0 -0
  115. package/python/Lib/__pycache__/traceback.cpython-313.pyc +0 -0
  116. package/python/Lib/__pycache__/types.cpython-313.pyc +0 -0
  117. package/python/Lib/__pycache__/typing.cpython-313.pyc +0 -0
  118. package/python/Lib/__pycache__/uuid.cpython-313.pyc +0 -0
  119. package/python/Lib/__pycache__/warnings.cpython-313.pyc +0 -0
  120. package/python/Lib/__pycache__/weakref.cpython-313.pyc +0 -0
  121. package/python/Lib/_aix_support.py +108 -0
  122. package/python/Lib/_android_support.py +192 -0
  123. package/python/Lib/_apple_support.py +66 -0
  124. package/python/Lib/_collections_abc.py +1187 -0
  125. package/python/Lib/_colorize.py +119 -0
  126. package/python/Lib/_compat_pickle.py +251 -0
  127. package/python/Lib/_compression.py +162 -0
  128. package/python/Lib/_ios_support.py +71 -0
  129. package/python/Lib/_markupbase.py +396 -0
  130. package/python/Lib/_opcode_metadata.py +343 -0
  131. package/python/Lib/_osx_support.py +579 -0
  132. package/python/Lib/_py_abc.py +147 -0
  133. package/python/Lib/_pydatetime.py +2640 -0
  134. package/python/Lib/_pydecimal.py +6356 -0
  135. package/python/Lib/_pyio.py +2714 -0
  136. package/python/Lib/_pylong.py +363 -0
  137. package/python/Lib/_pyrepl/__init__.py +19 -0
  138. package/python/Lib/_pyrepl/__main__.py +10 -0
  139. package/python/Lib/_pyrepl/_minimal_curses.py +68 -0
  140. package/python/Lib/_pyrepl/_threading_handler.py +74 -0
  141. package/python/Lib/_pyrepl/base_eventqueue.py +110 -0
  142. package/python/Lib/_pyrepl/commands.py +492 -0
  143. package/python/Lib/_pyrepl/completing_reader.py +295 -0
  144. package/python/Lib/_pyrepl/console.py +229 -0
  145. package/python/Lib/_pyrepl/curses.py +33 -0
  146. package/python/Lib/_pyrepl/fancy_termios.py +82 -0
  147. package/python/Lib/_pyrepl/historical_reader.py +419 -0
  148. package/python/Lib/_pyrepl/input.py +114 -0
  149. package/python/Lib/_pyrepl/keymap.py +213 -0
  150. package/python/Lib/_pyrepl/main.py +59 -0
  151. package/python/Lib/_pyrepl/mypy.ini +29 -0
  152. package/python/Lib/_pyrepl/pager.py +175 -0
  153. package/python/Lib/_pyrepl/reader.py +764 -0
  154. package/python/Lib/_pyrepl/readline.py +599 -0
  155. package/python/Lib/_pyrepl/simple_interact.py +180 -0
  156. package/python/Lib/_pyrepl/trace.py +21 -0
  157. package/python/Lib/_pyrepl/types.py +10 -0
  158. package/python/Lib/_pyrepl/unix_console.py +852 -0
  159. package/python/Lib/_pyrepl/unix_eventqueue.py +76 -0
  160. package/python/Lib/_pyrepl/utils.py +83 -0
  161. package/python/Lib/_pyrepl/windows_console.py +687 -0
  162. package/python/Lib/_pyrepl/windows_eventqueue.py +42 -0
  163. package/python/Lib/_sitebuiltins.py +91 -0
  164. package/python/Lib/_strptime.py +800 -0
  165. package/python/Lib/_threading_local.py +120 -0
  166. package/python/Lib/_weakrefset.py +205 -0
  167. package/python/Lib/abc.py +188 -0
  168. package/python/Lib/antigravity.py +17 -0
  169. package/python/Lib/argparse.py +2690 -0
  170. package/python/Lib/ast.py +1865 -0
  171. package/python/Lib/asyncio/__init__.py +47 -0
  172. package/python/Lib/asyncio/__main__.py +211 -0
  173. package/python/Lib/asyncio/base_events.py +2086 -0
  174. package/python/Lib/asyncio/base_futures.py +67 -0
  175. package/python/Lib/asyncio/base_subprocess.py +312 -0
  176. package/python/Lib/asyncio/base_tasks.py +94 -0
  177. package/python/Lib/asyncio/constants.py +41 -0
  178. package/python/Lib/asyncio/coroutines.py +109 -0
  179. package/python/Lib/asyncio/events.py +885 -0
  180. package/python/Lib/asyncio/exceptions.py +62 -0
  181. package/python/Lib/asyncio/format_helpers.py +84 -0
  182. package/python/Lib/asyncio/futures.py +425 -0
  183. package/python/Lib/asyncio/locks.py +617 -0
  184. package/python/Lib/asyncio/log.py +7 -0
  185. package/python/Lib/asyncio/mixins.py +21 -0
  186. package/python/Lib/asyncio/proactor_events.py +891 -0
  187. package/python/Lib/asyncio/protocols.py +216 -0
  188. package/python/Lib/asyncio/queues.py +309 -0
  189. package/python/Lib/asyncio/runners.py +217 -0
  190. package/python/Lib/asyncio/selector_events.py +1328 -0
  191. package/python/Lib/asyncio/sslproto.py +929 -0
  192. package/python/Lib/asyncio/staggered.py +174 -0
  193. package/python/Lib/asyncio/streams.py +787 -0
  194. package/python/Lib/asyncio/subprocess.py +229 -0
  195. package/python/Lib/asyncio/taskgroups.py +278 -0
  196. package/python/Lib/asyncio/tasks.py +1121 -0
  197. package/python/Lib/asyncio/threads.py +26 -0
  198. package/python/Lib/asyncio/timeouts.py +185 -0
  199. package/python/Lib/asyncio/transports.py +337 -0
  200. package/python/Lib/asyncio/trsock.py +98 -0
  201. package/python/Lib/asyncio/unix_events.py +1550 -0
  202. package/python/Lib/asyncio/windows_events.py +906 -0
  203. package/python/Lib/asyncio/windows_utils.py +181 -0
  204. package/python/Lib/base64.py +628 -0
  205. package/python/Lib/bdb.py +973 -0
  206. package/python/Lib/bisect.py +118 -0
  207. package/python/Lib/bz2.py +352 -0
  208. package/python/Lib/cProfile.py +197 -0
  209. package/python/Lib/calendar.py +813 -0
  210. package/python/Lib/cmd.py +409 -0
  211. package/python/Lib/code.py +386 -0
  212. package/python/Lib/codecs.py +1132 -0
  213. package/python/Lib/codeop.py +155 -0
  214. package/python/Lib/collections/__init__.py +1603 -0
  215. package/python/Lib/collections/__pycache__/__init__.cpython-313.pyc +0 -0
  216. package/python/Lib/colorsys.py +166 -0
  217. package/python/Lib/compileall.py +470 -0
  218. package/python/Lib/concurrent/__init__.py +1 -0
  219. package/python/Lib/concurrent/futures/__init__.py +54 -0
  220. package/python/Lib/concurrent/futures/_base.py +660 -0
  221. package/python/Lib/concurrent/futures/process.py +892 -0
  222. package/python/Lib/concurrent/futures/thread.py +240 -0
  223. package/python/Lib/configparser.py +1396 -0
  224. package/python/Lib/contextlib.py +814 -0
  225. package/python/Lib/contextvars.py +4 -0
  226. package/python/Lib/copy.py +306 -0
  227. package/python/Lib/copyreg.py +217 -0
  228. package/python/Lib/csv.py +527 -0
  229. package/python/Lib/ctypes/__init__.py +602 -0
  230. package/python/Lib/ctypes/__pycache__/__init__.cpython-313.pyc +0 -0
  231. package/python/Lib/ctypes/__pycache__/_endian.cpython-313.pyc +0 -0
  232. package/python/Lib/ctypes/__pycache__/wintypes.cpython-313.pyc +0 -0
  233. package/python/Lib/ctypes/_aix.py +327 -0
  234. package/python/Lib/ctypes/_endian.py +78 -0
  235. package/python/Lib/ctypes/macholib/README.ctypes +7 -0
  236. package/python/Lib/ctypes/macholib/__init__.py +9 -0
  237. package/python/Lib/ctypes/macholib/dyld.py +165 -0
  238. package/python/Lib/ctypes/macholib/dylib.py +42 -0
  239. package/python/Lib/ctypes/macholib/fetch_macholib +2 -0
  240. package/python/Lib/ctypes/macholib/fetch_macholib.bat +1 -0
  241. package/python/Lib/ctypes/macholib/framework.py +42 -0
  242. package/python/Lib/ctypes/util.py +387 -0
  243. package/python/Lib/ctypes/wintypes.py +202 -0
  244. package/python/Lib/curses/__init__.py +101 -0
  245. package/python/Lib/curses/ascii.py +99 -0
  246. package/python/Lib/curses/has_key.py +192 -0
  247. package/python/Lib/curses/panel.py +6 -0
  248. package/python/Lib/curses/textpad.py +236 -0
  249. package/python/Lib/dataclasses.py +1679 -0
  250. package/python/Lib/datetime.py +9 -0
  251. package/python/Lib/dbm/__init__.py +194 -0
  252. package/python/Lib/dbm/dumb.py +319 -0
  253. package/python/Lib/dbm/gnu.py +3 -0
  254. package/python/Lib/dbm/ndbm.py +3 -0
  255. package/python/Lib/dbm/sqlite3.py +144 -0
  256. package/python/Lib/decimal.py +109 -0
  257. package/python/Lib/difflib.py +2058 -0
  258. package/python/Lib/dis.py +1075 -0
  259. package/python/Lib/doctest.py +2919 -0
  260. package/python/Lib/email/__init__.py +61 -0
  261. package/python/Lib/email/__pycache__/__init__.cpython-313.pyc +0 -0
  262. package/python/Lib/email/__pycache__/_encoded_words.cpython-313.pyc +0 -0
  263. package/python/Lib/email/__pycache__/_parseaddr.cpython-313.pyc +0 -0
  264. package/python/Lib/email/__pycache__/_policybase.cpython-313.pyc +0 -0
  265. package/python/Lib/email/__pycache__/base64mime.cpython-313.pyc +0 -0
  266. package/python/Lib/email/__pycache__/charset.cpython-313.pyc +0 -0
  267. package/python/Lib/email/__pycache__/encoders.cpython-313.pyc +0 -0
  268. package/python/Lib/email/__pycache__/errors.cpython-313.pyc +0 -0
  269. package/python/Lib/email/__pycache__/feedparser.cpython-313.pyc +0 -0
  270. package/python/Lib/email/__pycache__/header.cpython-313.pyc +0 -0
  271. package/python/Lib/email/__pycache__/iterators.cpython-313.pyc +0 -0
  272. package/python/Lib/email/__pycache__/message.cpython-313.pyc +0 -0
  273. package/python/Lib/email/__pycache__/parser.cpython-313.pyc +0 -0
  274. package/python/Lib/email/__pycache__/quoprimime.cpython-313.pyc +0 -0
  275. package/python/Lib/email/__pycache__/utils.cpython-313.pyc +0 -0
  276. package/python/Lib/email/_encoded_words.py +233 -0
  277. package/python/Lib/email/_header_value_parser.py +3153 -0
  278. package/python/Lib/email/_parseaddr.py +563 -0
  279. package/python/Lib/email/_policybase.py +382 -0
  280. package/python/Lib/email/architecture.rst +216 -0
  281. package/python/Lib/email/base64mime.py +115 -0
  282. package/python/Lib/email/charset.py +396 -0
  283. package/python/Lib/email/contentmanager.py +254 -0
  284. package/python/Lib/email/encoders.py +65 -0
  285. package/python/Lib/email/errors.py +117 -0
  286. package/python/Lib/email/feedparser.py +536 -0
  287. package/python/Lib/email/generator.py +530 -0
  288. package/python/Lib/email/header.py +582 -0
  289. package/python/Lib/email/headerregistry.py +618 -0
  290. package/python/Lib/email/iterators.py +68 -0
  291. package/python/Lib/email/message.py +1217 -0
  292. package/python/Lib/email/mime/__init__.py +0 -0
  293. package/python/Lib/email/mime/application.py +37 -0
  294. package/python/Lib/email/mime/audio.py +97 -0
  295. package/python/Lib/email/mime/base.py +29 -0
  296. package/python/Lib/email/mime/image.py +152 -0
  297. package/python/Lib/email/mime/message.py +33 -0
  298. package/python/Lib/email/mime/multipart.py +47 -0
  299. package/python/Lib/email/mime/nonmultipart.py +21 -0
  300. package/python/Lib/email/mime/text.py +40 -0
  301. package/python/Lib/email/parser.py +127 -0
  302. package/python/Lib/email/policy.py +232 -0
  303. package/python/Lib/email/quoprimime.py +300 -0
  304. package/python/Lib/email/utils.py +497 -0
  305. package/python/Lib/encodings/__init__.py +179 -0
  306. package/python/Lib/encodings/__pycache__/__init__.cpython-313.pyc +0 -0
  307. package/python/Lib/encodings/__pycache__/aliases.cpython-313.pyc +0 -0
  308. package/python/Lib/encodings/__pycache__/cp1252.cpython-313.pyc +0 -0
  309. package/python/Lib/encodings/__pycache__/cp437.cpython-313.pyc +0 -0
  310. package/python/Lib/encodings/__pycache__/hex_codec.cpython-313.pyc +0 -0
  311. package/python/Lib/encodings/__pycache__/idna.cpython-313.pyc +0 -0
  312. package/python/Lib/encodings/__pycache__/utf_8.cpython-313.pyc +0 -0
  313. package/python/Lib/encodings/aliases.py +560 -0
  314. package/python/Lib/encodings/ascii.py +50 -0
  315. package/python/Lib/encodings/base64_codec.py +55 -0
  316. package/python/Lib/encodings/big5.py +39 -0
  317. package/python/Lib/encodings/big5hkscs.py +39 -0
  318. package/python/Lib/encodings/bz2_codec.py +78 -0
  319. package/python/Lib/encodings/charmap.py +69 -0
  320. package/python/Lib/encodings/cp037.py +307 -0
  321. package/python/Lib/encodings/cp1006.py +307 -0
  322. package/python/Lib/encodings/cp1026.py +307 -0
  323. package/python/Lib/encodings/cp1125.py +698 -0
  324. package/python/Lib/encodings/cp1140.py +307 -0
  325. package/python/Lib/encodings/cp1250.py +307 -0
  326. package/python/Lib/encodings/cp1251.py +307 -0
  327. package/python/Lib/encodings/cp1252.py +307 -0
  328. package/python/Lib/encodings/cp1253.py +307 -0
  329. package/python/Lib/encodings/cp1254.py +307 -0
  330. package/python/Lib/encodings/cp1255.py +307 -0
  331. package/python/Lib/encodings/cp1256.py +307 -0
  332. package/python/Lib/encodings/cp1257.py +307 -0
  333. package/python/Lib/encodings/cp1258.py +307 -0
  334. package/python/Lib/encodings/cp273.py +307 -0
  335. package/python/Lib/encodings/cp424.py +307 -0
  336. package/python/Lib/encodings/cp437.py +698 -0
  337. package/python/Lib/encodings/cp500.py +307 -0
  338. package/python/Lib/encodings/cp720.py +309 -0
  339. package/python/Lib/encodings/cp737.py +698 -0
  340. package/python/Lib/encodings/cp775.py +697 -0
  341. package/python/Lib/encodings/cp850.py +698 -0
  342. package/python/Lib/encodings/cp852.py +698 -0
  343. package/python/Lib/encodings/cp855.py +698 -0
  344. package/python/Lib/encodings/cp856.py +307 -0
  345. package/python/Lib/encodings/cp857.py +694 -0
  346. package/python/Lib/encodings/cp858.py +698 -0
  347. package/python/Lib/encodings/cp860.py +698 -0
  348. package/python/Lib/encodings/cp861.py +698 -0
  349. package/python/Lib/encodings/cp862.py +698 -0
  350. package/python/Lib/encodings/cp863.py +698 -0
  351. package/python/Lib/encodings/cp864.py +690 -0
  352. package/python/Lib/encodings/cp865.py +698 -0
  353. package/python/Lib/encodings/cp866.py +698 -0
  354. package/python/Lib/encodings/cp869.py +689 -0
  355. package/python/Lib/encodings/cp874.py +307 -0
  356. package/python/Lib/encodings/cp875.py +307 -0
  357. package/python/Lib/encodings/cp932.py +39 -0
  358. package/python/Lib/encodings/cp949.py +39 -0
  359. package/python/Lib/encodings/cp950.py +39 -0
  360. package/python/Lib/encodings/euc_jis_2004.py +39 -0
  361. package/python/Lib/encodings/euc_jisx0213.py +39 -0
  362. package/python/Lib/encodings/euc_jp.py +39 -0
  363. package/python/Lib/encodings/euc_kr.py +39 -0
  364. package/python/Lib/encodings/gb18030.py +39 -0
  365. package/python/Lib/encodings/gb2312.py +39 -0
  366. package/python/Lib/encodings/gbk.py +39 -0
  367. package/python/Lib/encodings/hex_codec.py +55 -0
  368. package/python/Lib/encodings/hp_roman8.py +314 -0
  369. package/python/Lib/encodings/hz.py +39 -0
  370. package/python/Lib/encodings/idna.py +387 -0
  371. package/python/Lib/encodings/iso2022_jp.py +39 -0
  372. package/python/Lib/encodings/iso2022_jp_1.py +39 -0
  373. package/python/Lib/encodings/iso2022_jp_2.py +39 -0
  374. package/python/Lib/encodings/iso2022_jp_2004.py +39 -0
  375. package/python/Lib/encodings/iso2022_jp_3.py +39 -0
  376. package/python/Lib/encodings/iso2022_jp_ext.py +39 -0
  377. package/python/Lib/encodings/iso2022_kr.py +39 -0
  378. package/python/Lib/encodings/iso8859_1.py +307 -0
  379. package/python/Lib/encodings/iso8859_10.py +307 -0
  380. package/python/Lib/encodings/iso8859_11.py +307 -0
  381. package/python/Lib/encodings/iso8859_13.py +307 -0
  382. package/python/Lib/encodings/iso8859_14.py +307 -0
  383. package/python/Lib/encodings/iso8859_15.py +307 -0
  384. package/python/Lib/encodings/iso8859_16.py +307 -0
  385. package/python/Lib/encodings/iso8859_2.py +307 -0
  386. package/python/Lib/encodings/iso8859_3.py +307 -0
  387. package/python/Lib/encodings/iso8859_4.py +307 -0
  388. package/python/Lib/encodings/iso8859_5.py +307 -0
  389. package/python/Lib/encodings/iso8859_6.py +307 -0
  390. package/python/Lib/encodings/iso8859_7.py +307 -0
  391. package/python/Lib/encodings/iso8859_8.py +307 -0
  392. package/python/Lib/encodings/iso8859_9.py +307 -0
  393. package/python/Lib/encodings/johab.py +39 -0
  394. package/python/Lib/encodings/koi8_r.py +307 -0
  395. package/python/Lib/encodings/koi8_t.py +308 -0
  396. package/python/Lib/encodings/koi8_u.py +307 -0
  397. package/python/Lib/encodings/kz1048.py +307 -0
  398. package/python/Lib/encodings/latin_1.py +50 -0
  399. package/python/Lib/encodings/mac_arabic.py +698 -0
  400. package/python/Lib/encodings/mac_croatian.py +307 -0
  401. package/python/Lib/encodings/mac_cyrillic.py +307 -0
  402. package/python/Lib/encodings/mac_farsi.py +307 -0
  403. package/python/Lib/encodings/mac_greek.py +307 -0
  404. package/python/Lib/encodings/mac_iceland.py +307 -0
  405. package/python/Lib/encodings/mac_latin2.py +312 -0
  406. package/python/Lib/encodings/mac_roman.py +307 -0
  407. package/python/Lib/encodings/mac_romanian.py +307 -0
  408. package/python/Lib/encodings/mac_turkish.py +307 -0
  409. package/python/Lib/encodings/mbcs.py +47 -0
  410. package/python/Lib/encodings/oem.py +41 -0
  411. package/python/Lib/encodings/palmos.py +308 -0
  412. package/python/Lib/encodings/ptcp154.py +312 -0
  413. package/python/Lib/encodings/punycode.py +253 -0
  414. package/python/Lib/encodings/quopri_codec.py +56 -0
  415. package/python/Lib/encodings/raw_unicode_escape.py +46 -0
  416. package/python/Lib/encodings/rot_13.py +113 -0
  417. package/python/Lib/encodings/shift_jis.py +39 -0
  418. package/python/Lib/encodings/shift_jis_2004.py +39 -0
  419. package/python/Lib/encodings/shift_jisx0213.py +39 -0
  420. package/python/Lib/encodings/tis_620.py +307 -0
  421. package/python/Lib/encodings/undefined.py +49 -0
  422. package/python/Lib/encodings/unicode_escape.py +46 -0
  423. package/python/Lib/encodings/utf_16.py +155 -0
  424. package/python/Lib/encodings/utf_16_be.py +42 -0
  425. package/python/Lib/encodings/utf_16_le.py +42 -0
  426. package/python/Lib/encodings/utf_32.py +150 -0
  427. package/python/Lib/encodings/utf_32_be.py +37 -0
  428. package/python/Lib/encodings/utf_32_le.py +37 -0
  429. package/python/Lib/encodings/utf_7.py +38 -0
  430. package/python/Lib/encodings/utf_8.py +42 -0
  431. package/python/Lib/encodings/utf_8_sig.py +130 -0
  432. package/python/Lib/encodings/uu_codec.py +103 -0
  433. package/python/Lib/encodings/zlib_codec.py +77 -0
  434. package/python/Lib/enum.py +2183 -0
  435. package/python/Lib/filecmp.py +320 -0
  436. package/python/Lib/fileinput.py +442 -0
  437. package/python/Lib/fnmatch.py +192 -0
  438. package/python/Lib/fractions.py +1043 -0
  439. package/python/Lib/ftplib.py +975 -0
  440. package/python/Lib/functools.py +1036 -0
  441. package/python/Lib/genericpath.py +200 -0
  442. package/python/Lib/getopt.py +215 -0
  443. package/python/Lib/getpass.py +192 -0
  444. package/python/Lib/gettext.py +657 -0
  445. package/python/Lib/glob.py +572 -0
  446. package/python/Lib/graphlib.py +250 -0
  447. package/python/Lib/gzip.py +693 -0
  448. package/python/Lib/hashlib.py +255 -0
  449. package/python/Lib/heapq.py +603 -0
  450. package/python/Lib/hmac.py +220 -0
  451. package/python/Lib/html/__init__.py +132 -0
  452. package/python/Lib/html/__pycache__/__init__.cpython-313.pyc +0 -0
  453. package/python/Lib/html/__pycache__/entities.cpython-313.pyc +0 -0
  454. package/python/Lib/html/__pycache__/parser.cpython-313.pyc +0 -0
  455. package/python/Lib/html/entities.py +2513 -0
  456. package/python/Lib/html/parser.py +583 -0
  457. package/python/Lib/http/__init__.py +202 -0
  458. package/python/Lib/http/__pycache__/__init__.cpython-313.pyc +0 -0
  459. package/python/Lib/http/__pycache__/client.cpython-313.pyc +0 -0
  460. package/python/Lib/http/__pycache__/cookiejar.cpython-313.pyc +0 -0
  461. package/python/Lib/http/__pycache__/cookies.cpython-313.pyc +0 -0
  462. package/python/Lib/http/client.py +1598 -0
  463. package/python/Lib/http/cookiejar.py +2122 -0
  464. package/python/Lib/http/cookies.py +635 -0
  465. package/python/Lib/http/server.py +1355 -0
  466. package/python/Lib/imaplib.py +1769 -0
  467. package/python/Lib/importlib/__init__.py +136 -0
  468. package/python/Lib/importlib/__pycache__/__init__.cpython-313.pyc +0 -0
  469. package/python/Lib/importlib/__pycache__/_abc.cpython-313.pyc +0 -0
  470. package/python/Lib/importlib/__pycache__/abc.cpython-313.pyc +0 -0
  471. package/python/Lib/importlib/__pycache__/readers.cpython-313.pyc +0 -0
  472. package/python/Lib/importlib/_abc.py +39 -0
  473. package/python/Lib/importlib/_bootstrap.py +1559 -0
  474. package/python/Lib/importlib/_bootstrap_external.py +1826 -0
  475. package/python/Lib/importlib/abc.py +243 -0
  476. package/python/Lib/importlib/machinery.py +21 -0
  477. package/python/Lib/importlib/metadata/__init__.py +1093 -0
  478. package/python/Lib/importlib/metadata/__pycache__/__init__.cpython-313.pyc +0 -0
  479. package/python/Lib/importlib/metadata/__pycache__/_adapters.cpython-313.pyc +0 -0
  480. package/python/Lib/importlib/metadata/__pycache__/_collections.cpython-313.pyc +0 -0
  481. package/python/Lib/importlib/metadata/__pycache__/_functools.cpython-313.pyc +0 -0
  482. package/python/Lib/importlib/metadata/__pycache__/_itertools.cpython-313.pyc +0 -0
  483. package/python/Lib/importlib/metadata/__pycache__/_meta.cpython-313.pyc +0 -0
  484. package/python/Lib/importlib/metadata/__pycache__/_text.cpython-313.pyc +0 -0
  485. package/python/Lib/importlib/metadata/_adapters.py +89 -0
  486. package/python/Lib/importlib/metadata/_collections.py +30 -0
  487. package/python/Lib/importlib/metadata/_functools.py +104 -0
  488. package/python/Lib/importlib/metadata/_itertools.py +73 -0
  489. package/python/Lib/importlib/metadata/_meta.py +67 -0
  490. package/python/Lib/importlib/metadata/_text.py +99 -0
  491. package/python/Lib/importlib/metadata/diagnose.py +21 -0
  492. package/python/Lib/importlib/readers.py +12 -0
  493. package/python/Lib/importlib/resources/__init__.py +43 -0
  494. package/python/Lib/importlib/resources/__pycache__/__init__.cpython-313.pyc +0 -0
  495. package/python/Lib/importlib/resources/__pycache__/_adapters.cpython-313.pyc +0 -0
  496. package/python/Lib/importlib/resources/__pycache__/_common.cpython-313.pyc +0 -0
  497. package/python/Lib/importlib/resources/__pycache__/_functional.cpython-313.pyc +0 -0
  498. package/python/Lib/importlib/resources/__pycache__/_itertools.cpython-313.pyc +0 -0
  499. package/python/Lib/importlib/resources/__pycache__/abc.cpython-313.pyc +0 -0
  500. package/python/Lib/importlib/resources/__pycache__/readers.cpython-313.pyc +0 -0
  501. package/python/Lib/importlib/resources/_adapters.py +168 -0
  502. package/python/Lib/importlib/resources/_common.py +211 -0
  503. package/python/Lib/importlib/resources/_functional.py +81 -0
  504. package/python/Lib/importlib/resources/_itertools.py +38 -0
  505. package/python/Lib/importlib/resources/abc.py +173 -0
  506. package/python/Lib/importlib/resources/readers.py +203 -0
  507. package/python/Lib/importlib/resources/simple.py +106 -0
  508. package/python/Lib/importlib/simple.py +14 -0
  509. package/python/Lib/importlib/util.py +274 -0
  510. package/python/Lib/inspect.py +3479 -0
  511. package/python/Lib/io.py +99 -0
  512. package/python/Lib/ipaddress.py +2440 -0
  513. package/python/Lib/json/__init__.py +365 -0
  514. package/python/Lib/json/__pycache__/__init__.cpython-313.pyc +0 -0
  515. package/python/Lib/json/__pycache__/decoder.cpython-313.pyc +0 -0
  516. package/python/Lib/json/__pycache__/encoder.cpython-313.pyc +0 -0
  517. package/python/Lib/json/__pycache__/scanner.cpython-313.pyc +0 -0
  518. package/python/Lib/json/decoder.py +364 -0
  519. package/python/Lib/json/encoder.py +446 -0
  520. package/python/Lib/json/scanner.py +73 -0
  521. package/python/Lib/json/tool.py +90 -0
  522. package/python/Lib/keyword.py +64 -0
  523. package/python/Lib/linecache.py +236 -0
  524. package/python/Lib/locale.py +1987 -0
  525. package/python/Lib/logging/__init__.py +2330 -0
  526. package/python/Lib/logging/__pycache__/__init__.cpython-313.pyc +0 -0
  527. package/python/Lib/logging/__pycache__/config.cpython-313.pyc +0 -0
  528. package/python/Lib/logging/__pycache__/handlers.cpython-313.pyc +0 -0
  529. package/python/Lib/logging/config.py +1080 -0
  530. package/python/Lib/logging/handlers.py +1629 -0
  531. package/python/Lib/lzma.py +364 -0
  532. package/python/Lib/mailbox.py +2219 -0
  533. package/python/Lib/mimetypes.py +679 -0
  534. package/python/Lib/modulefinder.py +671 -0
  535. package/python/Lib/multiprocessing/__init__.py +37 -0
  536. package/python/Lib/multiprocessing/connection.py +1216 -0
  537. package/python/Lib/multiprocessing/context.py +383 -0
  538. package/python/Lib/multiprocessing/dummy/__init__.py +126 -0
  539. package/python/Lib/multiprocessing/dummy/connection.py +75 -0
  540. package/python/Lib/multiprocessing/forkserver.py +373 -0
  541. package/python/Lib/multiprocessing/heap.py +337 -0
  542. package/python/Lib/multiprocessing/managers.py +1397 -0
  543. package/python/Lib/multiprocessing/pool.py +957 -0
  544. package/python/Lib/multiprocessing/popen_fork.py +97 -0
  545. package/python/Lib/multiprocessing/popen_forkserver.py +74 -0
  546. package/python/Lib/multiprocessing/popen_spawn_posix.py +76 -0
  547. package/python/Lib/multiprocessing/popen_spawn_win32.py +147 -0
  548. package/python/Lib/multiprocessing/process.py +436 -0
  549. package/python/Lib/multiprocessing/queues.py +399 -0
  550. package/python/Lib/multiprocessing/reduction.py +281 -0
  551. package/python/Lib/multiprocessing/resource_sharer.py +154 -0
  552. package/python/Lib/multiprocessing/resource_tracker.py +499 -0
  553. package/python/Lib/multiprocessing/shared_memory.py +544 -0
  554. package/python/Lib/multiprocessing/sharedctypes.py +240 -0
  555. package/python/Lib/multiprocessing/spawn.py +307 -0
  556. package/python/Lib/multiprocessing/synchronize.py +404 -0
  557. package/python/Lib/multiprocessing/util.py +562 -0
  558. package/python/Lib/netrc.py +199 -0
  559. package/python/Lib/ntpath.py +872 -0
  560. package/python/Lib/nturl2path.py +69 -0
  561. package/python/Lib/numbers.py +427 -0
  562. package/python/Lib/opcode.py +115 -0
  563. package/python/Lib/operator.py +467 -0
  564. package/python/Lib/optparse.py +1681 -0
  565. package/python/Lib/os.py +1184 -0
  566. package/python/Lib/pathlib/__init__.py +12 -0
  567. package/python/Lib/pathlib/__pycache__/__init__.cpython-313.pyc +0 -0
  568. package/python/Lib/pathlib/__pycache__/_abc.cpython-313.pyc +0 -0
  569. package/python/Lib/pathlib/__pycache__/_local.cpython-313.pyc +0 -0
  570. package/python/Lib/pathlib/_abc.py +930 -0
  571. package/python/Lib/pathlib/_local.py +861 -0
  572. package/python/Lib/pdb.py +2550 -0
  573. package/python/Lib/pickle.py +1860 -0
  574. package/python/Lib/pickletools.py +2904 -0
  575. package/python/Lib/pkgutil.py +529 -0
  576. package/python/Lib/platform.py +1454 -0
  577. package/python/Lib/plistlib.py +948 -0
  578. package/python/Lib/poplib.py +477 -0
  579. package/python/Lib/posixpath.py +578 -0
  580. package/python/Lib/pprint.py +658 -0
  581. package/python/Lib/profile.py +616 -0
  582. package/python/Lib/pstats.py +778 -0
  583. package/python/Lib/pty.py +211 -0
  584. package/python/Lib/py_compile.py +212 -0
  585. package/python/Lib/pyclbr.py +314 -0
  586. package/python/Lib/pydoc.py +2861 -0
  587. package/python/Lib/queue.py +383 -0
  588. package/python/Lib/quopri.py +237 -0
  589. package/python/Lib/random.py +1078 -0
  590. package/python/Lib/re/__init__.py +428 -0
  591. package/python/Lib/re/__pycache__/__init__.cpython-313.pyc +0 -0
  592. package/python/Lib/re/__pycache__/_casefix.cpython-313.pyc +0 -0
  593. package/python/Lib/re/__pycache__/_compiler.cpython-313.pyc +0 -0
  594. package/python/Lib/re/__pycache__/_constants.cpython-313.pyc +0 -0
  595. package/python/Lib/re/__pycache__/_parser.cpython-313.pyc +0 -0
  596. package/python/Lib/re/_casefix.py +106 -0
  597. package/python/Lib/re/_compiler.py +768 -0
  598. package/python/Lib/re/_constants.py +222 -0
  599. package/python/Lib/re/_parser.py +1081 -0
  600. package/python/Lib/reprlib.py +230 -0
  601. package/python/Lib/rlcompleter.py +222 -0
  602. package/python/Lib/runpy.py +326 -0
  603. package/python/Lib/sched.py +167 -0
  604. package/python/Lib/secrets.py +71 -0
  605. package/python/Lib/selectors.py +603 -0
  606. package/python/Lib/shelve.py +250 -0
  607. package/python/Lib/shlex.py +345 -0
  608. package/python/Lib/shutil.py +1569 -0
  609. package/python/Lib/signal.py +94 -0
  610. package/python/Lib/site.py +773 -0
  611. package/python/Lib/smtplib.py +1123 -0
  612. package/python/Lib/socket.py +988 -0
  613. package/python/Lib/socketserver.py +863 -0
  614. package/python/Lib/sqlite3/__init__.py +70 -0
  615. package/python/Lib/sqlite3/__main__.py +139 -0
  616. package/python/Lib/sqlite3/dbapi2.py +108 -0
  617. package/python/Lib/sqlite3/dump.py +118 -0
  618. package/python/Lib/sre_compile.py +7 -0
  619. package/python/Lib/sre_constants.py +7 -0
  620. package/python/Lib/sre_parse.py +7 -0
  621. package/python/Lib/ssl.py +1529 -0
  622. package/python/Lib/stat.py +212 -0
  623. package/python/Lib/statistics.py +1817 -0
  624. package/python/Lib/string.py +314 -0
  625. package/python/Lib/stringprep.py +272 -0
  626. package/python/Lib/struct.py +15 -0
  627. package/python/Lib/subprocess.py +2258 -0
  628. package/python/Lib/symtable.py +414 -0
  629. package/python/Lib/sysconfig/__init__.py +734 -0
  630. package/python/Lib/sysconfig/__main__.py +248 -0
  631. package/python/Lib/sysconfig/__pycache__/__init__.cpython-313.pyc +0 -0
  632. package/python/Lib/tabnanny.py +340 -0
  633. package/python/Lib/tarfile.py +3136 -0
  634. package/python/Lib/tempfile.py +958 -0
  635. package/python/Lib/textwrap.py +497 -0
  636. package/python/Lib/this.py +28 -0
  637. package/python/Lib/threading.py +1602 -0
  638. package/python/Lib/timeit.py +381 -0
  639. package/python/Lib/token.py +141 -0
  640. package/python/Lib/tokenize.py +592 -0
  641. package/python/Lib/tomllib/__init__.py +10 -0
  642. package/python/Lib/tomllib/__pycache__/__init__.cpython-313.pyc +0 -0
  643. package/python/Lib/tomllib/__pycache__/_parser.cpython-313.pyc +0 -0
  644. package/python/Lib/tomllib/__pycache__/_re.cpython-313.pyc +0 -0
  645. package/python/Lib/tomllib/__pycache__/_types.cpython-313.pyc +0 -0
  646. package/python/Lib/tomllib/_parser.py +703 -0
  647. package/python/Lib/tomllib/_re.py +107 -0
  648. package/python/Lib/tomllib/_types.py +10 -0
  649. package/python/Lib/tomllib/mypy.ini +15 -0
  650. package/python/Lib/trace.py +754 -0
  651. package/python/Lib/traceback.py +1639 -0
  652. package/python/Lib/tracemalloc.py +560 -0
  653. package/python/Lib/tty.py +73 -0
  654. package/python/Lib/types.py +346 -0
  655. package/python/Lib/typing.py +3846 -0
  656. package/python/Lib/unittest/__init__.py +80 -0
  657. package/python/Lib/unittest/__main__.py +18 -0
  658. package/python/Lib/unittest/_log.py +86 -0
  659. package/python/Lib/unittest/async_case.py +146 -0
  660. package/python/Lib/unittest/case.py +1478 -0
  661. package/python/Lib/unittest/loader.py +460 -0
  662. package/python/Lib/unittest/main.py +280 -0
  663. package/python/Lib/unittest/mock.py +3189 -0
  664. package/python/Lib/unittest/result.py +256 -0
  665. package/python/Lib/unittest/runner.py +292 -0
  666. package/python/Lib/unittest/signals.py +71 -0
  667. package/python/Lib/unittest/suite.py +379 -0
  668. package/python/Lib/unittest/util.py +170 -0
  669. package/python/Lib/urllib/__init__.py +0 -0
  670. package/python/Lib/urllib/__pycache__/__init__.cpython-313.pyc +0 -0
  671. package/python/Lib/urllib/__pycache__/error.cpython-313.pyc +0 -0
  672. package/python/Lib/urllib/__pycache__/parse.cpython-313.pyc +0 -0
  673. package/python/Lib/urllib/__pycache__/request.cpython-313.pyc +0 -0
  674. package/python/Lib/urllib/__pycache__/response.cpython-313.pyc +0 -0
  675. package/python/Lib/urllib/error.py +74 -0
  676. package/python/Lib/urllib/parse.py +1264 -0
  677. package/python/Lib/urllib/request.py +2796 -0
  678. package/python/Lib/urllib/response.py +84 -0
  679. package/python/Lib/urllib/robotparser.py +363 -0
  680. package/python/Lib/uuid.py +784 -0
  681. package/python/Lib/warnings.py +735 -0
  682. package/python/Lib/wave.py +665 -0
  683. package/python/Lib/weakref.py +674 -0
  684. package/python/Lib/webbrowser.py +724 -0
  685. package/python/Lib/wsgiref/__init__.py +25 -0
  686. package/python/Lib/wsgiref/handlers.py +575 -0
  687. package/python/Lib/wsgiref/headers.py +192 -0
  688. package/python/Lib/wsgiref/simple_server.py +161 -0
  689. package/python/Lib/wsgiref/types.py +54 -0
  690. package/python/Lib/wsgiref/util.py +159 -0
  691. package/python/Lib/wsgiref/validate.py +438 -0
  692. package/python/Lib/xml/__init__.py +20 -0
  693. package/python/Lib/xml/__pycache__/__init__.cpython-313.pyc +0 -0
  694. package/python/Lib/xml/dom/NodeFilter.py +27 -0
  695. package/python/Lib/xml/dom/__init__.py +140 -0
  696. package/python/Lib/xml/dom/domreg.py +99 -0
  697. package/python/Lib/xml/dom/expatbuilder.py +962 -0
  698. package/python/Lib/xml/dom/minicompat.py +109 -0
  699. package/python/Lib/xml/dom/minidom.py +2024 -0
  700. package/python/Lib/xml/dom/pulldom.py +336 -0
  701. package/python/Lib/xml/dom/xmlbuilder.py +389 -0
  702. package/python/Lib/xml/etree/ElementInclude.py +186 -0
  703. package/python/Lib/xml/etree/ElementPath.py +430 -0
  704. package/python/Lib/xml/etree/ElementTree.py +2116 -0
  705. package/python/Lib/xml/etree/__init__.py +33 -0
  706. package/python/Lib/xml/etree/cElementTree.py +3 -0
  707. package/python/Lib/xml/parsers/__init__.py +8 -0
  708. package/python/Lib/xml/parsers/__pycache__/__init__.cpython-313.pyc +0 -0
  709. package/python/Lib/xml/parsers/__pycache__/expat.cpython-313.pyc +0 -0
  710. package/python/Lib/xml/parsers/expat.py +8 -0
  711. package/python/Lib/xml/sax/__init__.py +94 -0
  712. package/python/Lib/xml/sax/_exceptions.py +127 -0
  713. package/python/Lib/xml/sax/expatreader.py +454 -0
  714. package/python/Lib/xml/sax/handler.py +387 -0
  715. package/python/Lib/xml/sax/saxutils.py +369 -0
  716. package/python/Lib/xml/sax/xmlreader.py +378 -0
  717. package/python/Lib/xmlrpc/__init__.py +1 -0
  718. package/python/Lib/xmlrpc/__pycache__/__init__.cpython-313.pyc +0 -0
  719. package/python/Lib/xmlrpc/__pycache__/client.cpython-313.pyc +0 -0
  720. package/python/Lib/xmlrpc/client.py +1503 -0
  721. package/python/Lib/xmlrpc/server.py +1002 -0
  722. package/python/Lib/zipapp.py +229 -0
  723. package/python/Lib/zipfile/__init__.py +2391 -0
  724. package/python/Lib/zipfile/__main__.py +4 -0
  725. package/python/Lib/zipfile/__pycache__/__init__.cpython-313.pyc +0 -0
  726. package/python/Lib/zipfile/_path/__init__.py +452 -0
  727. package/python/Lib/zipfile/_path/__pycache__/__init__.cpython-313.pyc +0 -0
  728. package/python/Lib/zipfile/_path/__pycache__/glob.cpython-313.pyc +0 -0
  729. package/python/Lib/zipfile/_path/glob.py +113 -0
  730. package/python/Lib/zipimport.py +803 -0
  731. package/python/Lib/zoneinfo/__init__.py +34 -0
  732. package/python/Lib/zoneinfo/_common.py +172 -0
  733. package/python/Lib/zoneinfo/_tzpath.py +189 -0
  734. package/python/Lib/zoneinfo/_zoneinfo.py +779 -0
  735. package/python/licenses/LICENSE.bdb.txt +126 -0
  736. package/python/licenses/LICENSE.bzip2.txt +37 -0
  737. package/python/licenses/LICENSE.cpython.txt +771 -0
  738. package/python/licenses/LICENSE.expat.txt +21 -0
  739. package/python/licenses/LICENSE.libX11.txt +942 -0
  740. package/python/licenses/LICENSE.libXau.txt +21 -0
  741. package/python/licenses/LICENSE.libedit.txt +29 -0
  742. package/python/licenses/LICENSE.libffi.txt +21 -0
  743. package/python/licenses/LICENSE.liblzma.txt +13 -0
  744. package/python/licenses/LICENSE.libuuid.txt +27 -0
  745. package/python/licenses/LICENSE.libxcb.txt +30 -0
  746. package/python/licenses/LICENSE.mpdecimal.txt +24 -0
  747. package/python/licenses/LICENSE.ncurses.txt +29 -0
  748. package/python/licenses/LICENSE.openssl-1.1.txt +124 -0
  749. package/python/licenses/LICENSE.openssl-3.txt +177 -0
  750. package/python/licenses/LICENSE.sqlite.txt +23 -0
  751. package/python/licenses/LICENSE.tcl.txt +40 -0
  752. package/python/licenses/LICENSE.tix.txt +54 -0
  753. package/python/licenses/LICENSE.zlib.txt +21 -0
  754. package/python/python.exe +0 -0
  755. package/python/python3.dll +0 -0
  756. package/python/python313.dll +0 -0
  757. package/python/pythonw.exe +0 -0
  758. package/python/vcruntime140.dll +0 -0
  759. package/python/vcruntime140_1.dll +0 -0
@@ -0,0 +1,3846 @@
1
+ """
2
+ The typing module: Support for gradual typing as defined by PEP 484 and subsequent PEPs.
3
+
4
+ Among other things, the module includes the following:
5
+ * Generic, Protocol, and internal machinery to support generic aliases.
6
+ All subscripted types like X[int], Union[int, str] are generic aliases.
7
+ * Various "special forms" that have unique meanings in type annotations:
8
+ Any, Never, ClassVar, Self, Concatenate, Unpack, and others.
9
+ * Classes whose instances can be type arguments to generic classes and functions:
10
+ TypeVar, ParamSpec, TypeVarTuple.
11
+ * Public helper functions: get_type_hints, overload, cast, final, and others.
12
+ * Several protocols to support duck-typing:
13
+ SupportsFloat, SupportsIndex, SupportsAbs, and others.
14
+ * Special types: NewType, NamedTuple, TypedDict.
15
+ * Deprecated aliases for builtin types and collections.abc ABCs.
16
+
17
+ Any name not present in __all__ is an implementation detail
18
+ that may be changed without notice. Use at your own risk!
19
+ """
20
+
21
+ from abc import abstractmethod, ABCMeta
22
+ import collections
23
+ from collections import defaultdict
24
+ import collections.abc
25
+ import copyreg
26
+ import functools
27
+ import operator
28
+ import sys
29
+ import types
30
+ from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType, GenericAlias
31
+
32
+ from _typing import (
33
+ _idfunc,
34
+ TypeVar,
35
+ ParamSpec,
36
+ TypeVarTuple,
37
+ ParamSpecArgs,
38
+ ParamSpecKwargs,
39
+ TypeAliasType,
40
+ Generic,
41
+ NoDefault,
42
+ )
43
+
44
+ # Please keep __all__ alphabetized within each category.
45
+ __all__ = [
46
+ # Super-special typing primitives.
47
+ 'Annotated',
48
+ 'Any',
49
+ 'Callable',
50
+ 'ClassVar',
51
+ 'Concatenate',
52
+ 'Final',
53
+ 'ForwardRef',
54
+ 'Generic',
55
+ 'Literal',
56
+ 'Optional',
57
+ 'ParamSpec',
58
+ 'Protocol',
59
+ 'Tuple',
60
+ 'Type',
61
+ 'TypeVar',
62
+ 'TypeVarTuple',
63
+ 'Union',
64
+
65
+ # ABCs (from collections.abc).
66
+ 'AbstractSet', # collections.abc.Set.
67
+ 'ByteString',
68
+ 'Container',
69
+ 'ContextManager',
70
+ 'Hashable',
71
+ 'ItemsView',
72
+ 'Iterable',
73
+ 'Iterator',
74
+ 'KeysView',
75
+ 'Mapping',
76
+ 'MappingView',
77
+ 'MutableMapping',
78
+ 'MutableSequence',
79
+ 'MutableSet',
80
+ 'Sequence',
81
+ 'Sized',
82
+ 'ValuesView',
83
+ 'Awaitable',
84
+ 'AsyncIterator',
85
+ 'AsyncIterable',
86
+ 'Coroutine',
87
+ 'Collection',
88
+ 'AsyncGenerator',
89
+ 'AsyncContextManager',
90
+
91
+ # Structural checks, a.k.a. protocols.
92
+ 'Reversible',
93
+ 'SupportsAbs',
94
+ 'SupportsBytes',
95
+ 'SupportsComplex',
96
+ 'SupportsFloat',
97
+ 'SupportsIndex',
98
+ 'SupportsInt',
99
+ 'SupportsRound',
100
+
101
+ # Concrete collection types.
102
+ 'ChainMap',
103
+ 'Counter',
104
+ 'Deque',
105
+ 'Dict',
106
+ 'DefaultDict',
107
+ 'List',
108
+ 'OrderedDict',
109
+ 'Set',
110
+ 'FrozenSet',
111
+ 'NamedTuple', # Not really a type.
112
+ 'TypedDict', # Not really a type.
113
+ 'Generator',
114
+
115
+ # Other concrete types.
116
+ 'BinaryIO',
117
+ 'IO',
118
+ 'Match',
119
+ 'Pattern',
120
+ 'TextIO',
121
+
122
+ # One-off things.
123
+ 'AnyStr',
124
+ 'assert_type',
125
+ 'assert_never',
126
+ 'cast',
127
+ 'clear_overloads',
128
+ 'dataclass_transform',
129
+ 'final',
130
+ 'get_args',
131
+ 'get_origin',
132
+ 'get_overloads',
133
+ 'get_protocol_members',
134
+ 'get_type_hints',
135
+ 'is_protocol',
136
+ 'is_typeddict',
137
+ 'LiteralString',
138
+ 'Never',
139
+ 'NewType',
140
+ 'no_type_check',
141
+ 'no_type_check_decorator',
142
+ 'NoDefault',
143
+ 'NoReturn',
144
+ 'NotRequired',
145
+ 'overload',
146
+ 'override',
147
+ 'ParamSpecArgs',
148
+ 'ParamSpecKwargs',
149
+ 'ReadOnly',
150
+ 'Required',
151
+ 'reveal_type',
152
+ 'runtime_checkable',
153
+ 'Self',
154
+ 'Text',
155
+ 'TYPE_CHECKING',
156
+ 'TypeAlias',
157
+ 'TypeGuard',
158
+ 'TypeIs',
159
+ 'TypeAliasType',
160
+ 'Unpack',
161
+ ]
162
+
163
+
164
+ def _type_convert(arg, module=None, *, allow_special_forms=False):
165
+ """For converting None to type(None), and strings to ForwardRef."""
166
+ if arg is None:
167
+ return type(None)
168
+ if isinstance(arg, str):
169
+ return ForwardRef(arg, module=module, is_class=allow_special_forms)
170
+ return arg
171
+
172
+
173
+ def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=False):
174
+ """Check that the argument is a type, and return it (internal helper).
175
+
176
+ As a special case, accept None and return type(None) instead. Also wrap strings
177
+ into ForwardRef instances. Consider several corner cases, for example plain
178
+ special forms like Union are not valid, while Union[int, str] is OK, etc.
179
+ The msg argument is a human-readable error message, e.g.::
180
+
181
+ "Union[arg, ...]: arg should be a type."
182
+
183
+ We append the repr() of the actual value (truncated to 100 chars).
184
+ """
185
+ invalid_generic_forms = (Generic, Protocol)
186
+ if not allow_special_forms:
187
+ invalid_generic_forms += (ClassVar,)
188
+ if is_argument:
189
+ invalid_generic_forms += (Final,)
190
+
191
+ arg = _type_convert(arg, module=module, allow_special_forms=allow_special_forms)
192
+ if (isinstance(arg, _GenericAlias) and
193
+ arg.__origin__ in invalid_generic_forms):
194
+ raise TypeError(f"{arg} is not valid as type argument")
195
+ if arg in (Any, LiteralString, NoReturn, Never, Self, TypeAlias):
196
+ return arg
197
+ if allow_special_forms and arg in (ClassVar, Final):
198
+ return arg
199
+ if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):
200
+ raise TypeError(f"Plain {arg} is not valid as type argument")
201
+ if type(arg) is tuple:
202
+ raise TypeError(f"{msg} Got {arg!r:.100}.")
203
+ return arg
204
+
205
+
206
+ def _is_param_expr(arg):
207
+ return arg is ... or isinstance(arg,
208
+ (tuple, list, ParamSpec, _ConcatenateGenericAlias))
209
+
210
+
211
+ def _should_unflatten_callable_args(typ, args):
212
+ """Internal helper for munging collections.abc.Callable's __args__.
213
+
214
+ The canonical representation for a Callable's __args__ flattens the
215
+ argument types, see https://github.com/python/cpython/issues/86361.
216
+
217
+ For example::
218
+
219
+ >>> import collections.abc
220
+ >>> P = ParamSpec('P')
221
+ >>> collections.abc.Callable[[int, int], str].__args__ == (int, int, str)
222
+ True
223
+ >>> collections.abc.Callable[P, str].__args__ == (P, str)
224
+ True
225
+
226
+ As a result, if we need to reconstruct the Callable from its __args__,
227
+ we need to unflatten it.
228
+ """
229
+ return (
230
+ typ.__origin__ is collections.abc.Callable
231
+ and not (len(args) == 2 and _is_param_expr(args[0]))
232
+ )
233
+
234
+
235
+ def _type_repr(obj):
236
+ """Return the repr() of an object, special-casing types (internal helper).
237
+
238
+ If obj is a type, we return a shorter version than the default
239
+ type.__repr__, based on the module and qualified name, which is
240
+ typically enough to uniquely identify a type. For everything
241
+ else, we fall back on repr(obj).
242
+ """
243
+ # When changing this function, don't forget about
244
+ # `_collections_abc._type_repr`, which does the same thing
245
+ # and must be consistent with this one.
246
+ if isinstance(obj, type):
247
+ if obj.__module__ == 'builtins':
248
+ return obj.__qualname__
249
+ return f'{obj.__module__}.{obj.__qualname__}'
250
+ if obj is ...:
251
+ return '...'
252
+ if isinstance(obj, types.FunctionType):
253
+ return obj.__name__
254
+ if isinstance(obj, tuple):
255
+ # Special case for `repr` of types with `ParamSpec`:
256
+ return '[' + ', '.join(_type_repr(t) for t in obj) + ']'
257
+ return repr(obj)
258
+
259
+
260
+ def _collect_type_parameters(args, *, enforce_default_ordering: bool = True):
261
+ """Collect all type parameters in args
262
+ in order of first appearance (lexicographic order).
263
+
264
+ For example::
265
+
266
+ >>> P = ParamSpec('P')
267
+ >>> T = TypeVar('T')
268
+ >>> _collect_type_parameters((T, Callable[P, T]))
269
+ (~T, ~P)
270
+ """
271
+ # required type parameter cannot appear after parameter with default
272
+ default_encountered = False
273
+ # or after TypeVarTuple
274
+ type_var_tuple_encountered = False
275
+ parameters = []
276
+ for t in args:
277
+ if isinstance(t, type):
278
+ # We don't want __parameters__ descriptor of a bare Python class.
279
+ pass
280
+ elif isinstance(t, tuple):
281
+ # `t` might be a tuple, when `ParamSpec` is substituted with
282
+ # `[T, int]`, or `[int, *Ts]`, etc.
283
+ for x in t:
284
+ for collected in _collect_type_parameters([x]):
285
+ if collected not in parameters:
286
+ parameters.append(collected)
287
+ elif hasattr(t, '__typing_subst__'):
288
+ if t not in parameters:
289
+ if enforce_default_ordering:
290
+ if type_var_tuple_encountered and t.has_default():
291
+ raise TypeError('Type parameter with a default'
292
+ ' follows TypeVarTuple')
293
+
294
+ if t.has_default():
295
+ default_encountered = True
296
+ elif default_encountered:
297
+ raise TypeError(f'Type parameter {t!r} without a default'
298
+ ' follows type parameter with a default')
299
+
300
+ parameters.append(t)
301
+ else:
302
+ if _is_unpacked_typevartuple(t):
303
+ type_var_tuple_encountered = True
304
+ for x in getattr(t, '__parameters__', ()):
305
+ if x not in parameters:
306
+ parameters.append(x)
307
+ return tuple(parameters)
308
+
309
+
310
+ def _check_generic_specialization(cls, arguments):
311
+ """Check correct count for parameters of a generic cls (internal helper).
312
+
313
+ This gives a nice error message in case of count mismatch.
314
+ """
315
+ expected_len = len(cls.__parameters__)
316
+ if not expected_len:
317
+ raise TypeError(f"{cls} is not a generic class")
318
+ actual_len = len(arguments)
319
+ if actual_len != expected_len:
320
+ # deal with defaults
321
+ if actual_len < expected_len:
322
+ # If the parameter at index `actual_len` in the parameters list
323
+ # has a default, then all parameters after it must also have
324
+ # one, because we validated as much in _collect_type_parameters().
325
+ # That means that no error needs to be raised here, despite
326
+ # the number of arguments being passed not matching the number
327
+ # of parameters: all parameters that aren't explicitly
328
+ # specialized in this call are parameters with default values.
329
+ if cls.__parameters__[actual_len].has_default():
330
+ return
331
+
332
+ expected_len -= sum(p.has_default() for p in cls.__parameters__)
333
+ expect_val = f"at least {expected_len}"
334
+ else:
335
+ expect_val = expected_len
336
+
337
+ raise TypeError(f"Too {'many' if actual_len > expected_len else 'few'} arguments"
338
+ f" for {cls}; actual {actual_len}, expected {expect_val}")
339
+
340
+
341
+ def _unpack_args(*args):
342
+ newargs = []
343
+ for arg in args:
344
+ subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
345
+ if subargs is not None and not (subargs and subargs[-1] is ...):
346
+ newargs.extend(subargs)
347
+ else:
348
+ newargs.append(arg)
349
+ return newargs
350
+
351
+ def _deduplicate(params, *, unhashable_fallback=False):
352
+ # Weed out strict duplicates, preserving the first of each occurrence.
353
+ try:
354
+ return dict.fromkeys(params)
355
+ except TypeError:
356
+ if not unhashable_fallback:
357
+ raise
358
+ # Happens for cases like `Annotated[dict, {'x': IntValidator()}]`
359
+ return _deduplicate_unhashable(params)
360
+
361
+ def _deduplicate_unhashable(unhashable_params):
362
+ new_unhashable = []
363
+ for t in unhashable_params:
364
+ if t not in new_unhashable:
365
+ new_unhashable.append(t)
366
+ return new_unhashable
367
+
368
+ def _compare_args_orderless(first_args, second_args):
369
+ first_unhashable = _deduplicate_unhashable(first_args)
370
+ second_unhashable = _deduplicate_unhashable(second_args)
371
+ t = list(second_unhashable)
372
+ try:
373
+ for elem in first_unhashable:
374
+ t.remove(elem)
375
+ except ValueError:
376
+ return False
377
+ return not t
378
+
379
+ def _remove_dups_flatten(parameters):
380
+ """Internal helper for Union creation and substitution.
381
+
382
+ Flatten Unions among parameters, then remove duplicates.
383
+ """
384
+ # Flatten out Union[Union[...], ...].
385
+ params = []
386
+ for p in parameters:
387
+ if isinstance(p, (_UnionGenericAlias, types.UnionType)):
388
+ params.extend(p.__args__)
389
+ else:
390
+ params.append(p)
391
+
392
+ return tuple(_deduplicate(params, unhashable_fallback=True))
393
+
394
+
395
+ def _flatten_literal_params(parameters):
396
+ """Internal helper for Literal creation: flatten Literals among parameters."""
397
+ params = []
398
+ for p in parameters:
399
+ if isinstance(p, _LiteralGenericAlias):
400
+ params.extend(p.__args__)
401
+ else:
402
+ params.append(p)
403
+ return tuple(params)
404
+
405
+
406
+ _cleanups = []
407
+ _caches = {}
408
+
409
+
410
+ def _tp_cache(func=None, /, *, typed=False):
411
+ """Internal wrapper caching __getitem__ of generic types.
412
+
413
+ For non-hashable arguments, the original function is used as a fallback.
414
+ """
415
+ def decorator(func):
416
+ # The callback 'inner' references the newly created lru_cache
417
+ # indirectly by performing a lookup in the global '_caches' dictionary.
418
+ # This breaks a reference that can be problematic when combined with
419
+ # C API extensions that leak references to types. See GH-98253.
420
+
421
+ cache = functools.lru_cache(typed=typed)(func)
422
+ _caches[func] = cache
423
+ _cleanups.append(cache.cache_clear)
424
+ del cache
425
+
426
+ @functools.wraps(func)
427
+ def inner(*args, **kwds):
428
+ try:
429
+ return _caches[func](*args, **kwds)
430
+ except TypeError:
431
+ pass # All real errors (not unhashable args) are raised below.
432
+ return func(*args, **kwds)
433
+ return inner
434
+
435
+ if func is not None:
436
+ return decorator(func)
437
+
438
+ return decorator
439
+
440
+
441
+ def _deprecation_warning_for_no_type_params_passed(funcname: str) -> None:
442
+ import warnings
443
+
444
+ depr_message = (
445
+ f"Failing to pass a value to the 'type_params' parameter "
446
+ f"of {funcname!r} is deprecated, as it leads to incorrect behaviour "
447
+ f"when calling {funcname} on a stringified annotation "
448
+ f"that references a PEP 695 type parameter. "
449
+ f"It will be disallowed in Python 3.15."
450
+ )
451
+ warnings.warn(depr_message, category=DeprecationWarning, stacklevel=3)
452
+
453
+
454
+ class _Sentinel:
455
+ __slots__ = ()
456
+ def __repr__(self):
457
+ return '<sentinel>'
458
+
459
+
460
+ _sentinel = _Sentinel()
461
+
462
+
463
+ def _eval_type(t, globalns, localns, type_params=_sentinel, *, recursive_guard=frozenset()):
464
+ """Evaluate all forward references in the given type t.
465
+
466
+ For use of globalns and localns see the docstring for get_type_hints().
467
+ recursive_guard is used to prevent infinite recursion with a recursive
468
+ ForwardRef.
469
+ """
470
+ if type_params is _sentinel:
471
+ _deprecation_warning_for_no_type_params_passed("typing._eval_type")
472
+ type_params = ()
473
+ if isinstance(t, ForwardRef):
474
+ return t._evaluate(globalns, localns, type_params, recursive_guard=recursive_guard)
475
+ if isinstance(t, (_GenericAlias, GenericAlias, types.UnionType)):
476
+ if isinstance(t, GenericAlias):
477
+ args = tuple(
478
+ ForwardRef(arg) if isinstance(arg, str) else arg
479
+ for arg in t.__args__
480
+ )
481
+ is_unpacked = t.__unpacked__
482
+ if _should_unflatten_callable_args(t, args):
483
+ t = t.__origin__[(args[:-1], args[-1])]
484
+ else:
485
+ t = t.__origin__[args]
486
+ if is_unpacked:
487
+ t = Unpack[t]
488
+
489
+ ev_args = tuple(
490
+ _eval_type(
491
+ a, globalns, localns, type_params, recursive_guard=recursive_guard
492
+ )
493
+ for a in t.__args__
494
+ )
495
+ if ev_args == t.__args__:
496
+ return t
497
+ if isinstance(t, GenericAlias):
498
+ return GenericAlias(t.__origin__, ev_args)
499
+ if isinstance(t, types.UnionType):
500
+ return functools.reduce(operator.or_, ev_args)
501
+ else:
502
+ return t.copy_with(ev_args)
503
+ return t
504
+
505
+
506
+ class _Final:
507
+ """Mixin to prohibit subclassing."""
508
+
509
+ __slots__ = ('__weakref__',)
510
+
511
+ def __init_subclass__(cls, /, *args, **kwds):
512
+ if '_root' not in kwds:
513
+ raise TypeError("Cannot subclass special typing classes")
514
+
515
+
516
+ class _NotIterable:
517
+ """Mixin to prevent iteration, without being compatible with Iterable.
518
+
519
+ That is, we could do::
520
+
521
+ def __iter__(self): raise TypeError()
522
+
523
+ But this would make users of this mixin duck type-compatible with
524
+ collections.abc.Iterable - isinstance(foo, Iterable) would be True.
525
+
526
+ Luckily, we can instead prevent iteration by setting __iter__ to None, which
527
+ is treated specially.
528
+ """
529
+
530
+ __slots__ = ()
531
+ __iter__ = None
532
+
533
+
534
+ # Internal indicator of special typing constructs.
535
+ # See __doc__ instance attribute for specific docs.
536
+ class _SpecialForm(_Final, _NotIterable, _root=True):
537
+ __slots__ = ('_name', '__doc__', '_getitem')
538
+
539
+ def __init__(self, getitem):
540
+ self._getitem = getitem
541
+ self._name = getitem.__name__
542
+ self.__doc__ = getitem.__doc__
543
+
544
+ def __getattr__(self, item):
545
+ if item in {'__name__', '__qualname__'}:
546
+ return self._name
547
+
548
+ raise AttributeError(item)
549
+
550
+ def __mro_entries__(self, bases):
551
+ raise TypeError(f"Cannot subclass {self!r}")
552
+
553
+ def __repr__(self):
554
+ return 'typing.' + self._name
555
+
556
+ def __reduce__(self):
557
+ return self._name
558
+
559
+ def __call__(self, *args, **kwds):
560
+ raise TypeError(f"Cannot instantiate {self!r}")
561
+
562
+ def __or__(self, other):
563
+ return Union[self, other]
564
+
565
+ def __ror__(self, other):
566
+ return Union[other, self]
567
+
568
+ def __instancecheck__(self, obj):
569
+ raise TypeError(f"{self} cannot be used with isinstance()")
570
+
571
+ def __subclasscheck__(self, cls):
572
+ raise TypeError(f"{self} cannot be used with issubclass()")
573
+
574
+ @_tp_cache
575
+ def __getitem__(self, parameters):
576
+ return self._getitem(self, parameters)
577
+
578
+
579
+ class _TypedCacheSpecialForm(_SpecialForm, _root=True):
580
+ def __getitem__(self, parameters):
581
+ if not isinstance(parameters, tuple):
582
+ parameters = (parameters,)
583
+ return self._getitem(self, *parameters)
584
+
585
+
586
+ class _AnyMeta(type):
587
+ def __instancecheck__(self, obj):
588
+ if self is Any:
589
+ raise TypeError("typing.Any cannot be used with isinstance()")
590
+ return super().__instancecheck__(obj)
591
+
592
+ def __repr__(self):
593
+ if self is Any:
594
+ return "typing.Any"
595
+ return super().__repr__() # respect to subclasses
596
+
597
+
598
+ class Any(metaclass=_AnyMeta):
599
+ """Special type indicating an unconstrained type.
600
+
601
+ - Any is assignable to every type.
602
+ - Any assumed to have all methods and attributes.
603
+ - All values are assignable to Any.
604
+
605
+ Note that all the above statements are true from the point of view of
606
+ static type checkers. At runtime, Any cannot be used with instance
607
+ checks.
608
+ """
609
+
610
+ def __new__(cls, *args, **kwargs):
611
+ if cls is Any:
612
+ raise TypeError("Any cannot be instantiated")
613
+ return super().__new__(cls)
614
+
615
+
616
+ @_SpecialForm
617
+ def NoReturn(self, parameters):
618
+ """Special type indicating functions that never return.
619
+
620
+ Example::
621
+
622
+ from typing import NoReturn
623
+
624
+ def stop() -> NoReturn:
625
+ raise Exception('no way')
626
+
627
+ NoReturn can also be used as a bottom type, a type that
628
+ has no values. Starting in Python 3.11, the Never type should
629
+ be used for this concept instead. Type checkers should treat the two
630
+ equivalently.
631
+ """
632
+ raise TypeError(f"{self} is not subscriptable")
633
+
634
+ # This is semantically identical to NoReturn, but it is implemented
635
+ # separately so that type checkers can distinguish between the two
636
+ # if they want.
637
+ @_SpecialForm
638
+ def Never(self, parameters):
639
+ """The bottom type, a type that has no members.
640
+
641
+ This can be used to define a function that should never be
642
+ called, or a function that never returns::
643
+
644
+ from typing import Never
645
+
646
+ def never_call_me(arg: Never) -> None:
647
+ pass
648
+
649
+ def int_or_str(arg: int | str) -> None:
650
+ never_call_me(arg) # type checker error
651
+ match arg:
652
+ case int():
653
+ print("It's an int")
654
+ case str():
655
+ print("It's a str")
656
+ case _:
657
+ never_call_me(arg) # OK, arg is of type Never
658
+ """
659
+ raise TypeError(f"{self} is not subscriptable")
660
+
661
+
662
+ @_SpecialForm
663
+ def Self(self, parameters):
664
+ """Used to spell the type of "self" in classes.
665
+
666
+ Example::
667
+
668
+ from typing import Self
669
+
670
+ class Foo:
671
+ def return_self(self) -> Self:
672
+ ...
673
+ return self
674
+
675
+ This is especially useful for:
676
+ - classmethods that are used as alternative constructors
677
+ - annotating an `__enter__` method which returns self
678
+ """
679
+ raise TypeError(f"{self} is not subscriptable")
680
+
681
+
682
+ @_SpecialForm
683
+ def LiteralString(self, parameters):
684
+ """Represents an arbitrary literal string.
685
+
686
+ Example::
687
+
688
+ from typing import LiteralString
689
+
690
+ def run_query(sql: LiteralString) -> None:
691
+ ...
692
+
693
+ def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
694
+ run_query("SELECT * FROM students") # OK
695
+ run_query(literal_string) # OK
696
+ run_query("SELECT * FROM " + literal_string) # OK
697
+ run_query(arbitrary_string) # type checker error
698
+ run_query( # type checker error
699
+ f"SELECT * FROM students WHERE name = {arbitrary_string}"
700
+ )
701
+
702
+ Only string literals and other LiteralStrings are compatible
703
+ with LiteralString. This provides a tool to help prevent
704
+ security issues such as SQL injection.
705
+ """
706
+ raise TypeError(f"{self} is not subscriptable")
707
+
708
+
709
+ @_SpecialForm
710
+ def ClassVar(self, parameters):
711
+ """Special type construct to mark class variables.
712
+
713
+ An annotation wrapped in ClassVar indicates that a given
714
+ attribute is intended to be used as a class variable and
715
+ should not be set on instances of that class.
716
+
717
+ Usage::
718
+
719
+ class Starship:
720
+ stats: ClassVar[dict[str, int]] = {} # class variable
721
+ damage: int = 10 # instance variable
722
+
723
+ ClassVar accepts only types and cannot be further subscribed.
724
+
725
+ Note that ClassVar is not a class itself, and cannot
726
+ be used with isinstance() or issubclass().
727
+ """
728
+ item = _type_check(parameters, f'{self} accepts only single type.', allow_special_forms=True)
729
+ return _GenericAlias(self, (item,))
730
+
731
+ @_SpecialForm
732
+ def Final(self, parameters):
733
+ """Special typing construct to indicate final names to type checkers.
734
+
735
+ A final name cannot be re-assigned or overridden in a subclass.
736
+
737
+ For example::
738
+
739
+ MAX_SIZE: Final = 9000
740
+ MAX_SIZE += 1 # Error reported by type checker
741
+
742
+ class Connection:
743
+ TIMEOUT: Final[int] = 10
744
+
745
+ class FastConnector(Connection):
746
+ TIMEOUT = 1 # Error reported by type checker
747
+
748
+ There is no runtime checking of these properties.
749
+ """
750
+ item = _type_check(parameters, f'{self} accepts only single type.', allow_special_forms=True)
751
+ return _GenericAlias(self, (item,))
752
+
753
+ @_SpecialForm
754
+ def Union(self, parameters):
755
+ """Union type; Union[X, Y] means either X or Y.
756
+
757
+ On Python 3.10 and higher, the | operator
758
+ can also be used to denote unions;
759
+ X | Y means the same thing to the type checker as Union[X, Y].
760
+
761
+ To define a union, use e.g. Union[int, str]. Details:
762
+ - The arguments must be types and there must be at least one.
763
+ - None as an argument is a special case and is replaced by
764
+ type(None).
765
+ - Unions of unions are flattened, e.g.::
766
+
767
+ assert Union[Union[int, str], float] == Union[int, str, float]
768
+
769
+ - Unions of a single argument vanish, e.g.::
770
+
771
+ assert Union[int] == int # The constructor actually returns int
772
+
773
+ - Redundant arguments are skipped, e.g.::
774
+
775
+ assert Union[int, str, int] == Union[int, str]
776
+
777
+ - When comparing unions, the argument order is ignored, e.g.::
778
+
779
+ assert Union[int, str] == Union[str, int]
780
+
781
+ - You cannot subclass or instantiate a union.
782
+ - You can use Optional[X] as a shorthand for Union[X, None].
783
+ """
784
+ if parameters == ():
785
+ raise TypeError("Cannot take a Union of no types.")
786
+ if not isinstance(parameters, tuple):
787
+ parameters = (parameters,)
788
+ msg = "Union[arg, ...]: each arg must be a type."
789
+ parameters = tuple(_type_check(p, msg) for p in parameters)
790
+ parameters = _remove_dups_flatten(parameters)
791
+ if len(parameters) == 1:
792
+ return parameters[0]
793
+ if len(parameters) == 2 and type(None) in parameters:
794
+ return _UnionGenericAlias(self, parameters, name="Optional")
795
+ return _UnionGenericAlias(self, parameters)
796
+
797
+ def _make_union(left, right):
798
+ """Used from the C implementation of TypeVar.
799
+
800
+ TypeVar.__or__ calls this instead of returning types.UnionType
801
+ because we want to allow unions between TypeVars and strings
802
+ (forward references).
803
+ """
804
+ return Union[left, right]
805
+
806
+ @_SpecialForm
807
+ def Optional(self, parameters):
808
+ """Optional[X] is equivalent to X | None."""
809
+ arg = _type_check(parameters, f"{self} requires a single type.")
810
+ return Union[arg, type(None)]
811
+
812
+ @_TypedCacheSpecialForm
813
+ @_tp_cache(typed=True)
814
+ def Literal(self, *parameters):
815
+ """Special typing form to define literal types (a.k.a. value types).
816
+
817
+ This form can be used to indicate to type checkers that the corresponding
818
+ variable or function parameter has a value equivalent to the provided
819
+ literal (or one of several literals)::
820
+
821
+ def validate_simple(data: Any) -> Literal[True]: # always returns True
822
+ ...
823
+
824
+ MODE = Literal['r', 'rb', 'w', 'wb']
825
+ def open_helper(file: str, mode: MODE) -> str:
826
+ ...
827
+
828
+ open_helper('/some/path', 'r') # Passes type check
829
+ open_helper('/other/path', 'typo') # Error in type checker
830
+
831
+ Literal[...] cannot be subclassed. At runtime, an arbitrary value
832
+ is allowed as type argument to Literal[...], but type checkers may
833
+ impose restrictions.
834
+ """
835
+ # There is no '_type_check' call because arguments to Literal[...] are
836
+ # values, not types.
837
+ parameters = _flatten_literal_params(parameters)
838
+ value_and_type_parameters = list(_value_and_type_iter(parameters))
839
+ deduplicated_parameters = tuple(
840
+ p
841
+ for p, _ in _deduplicate(
842
+ value_and_type_parameters,
843
+ unhashable_fallback=True,
844
+ )
845
+ )
846
+
847
+ return _LiteralGenericAlias(self, deduplicated_parameters)
848
+
849
+
850
+ @_SpecialForm
851
+ def TypeAlias(self, parameters):
852
+ """Special form for marking type aliases.
853
+
854
+ TypeAlias can be used to indicate that an assignment should
855
+ be recognized as a proper type alias definition by type
856
+ checkers.
857
+
858
+ For example::
859
+
860
+ Predicate: TypeAlias = Callable[..., bool]
861
+
862
+ It's invalid when used anywhere except as in the example above.
863
+ """
864
+ raise TypeError(f"{self} is not subscriptable")
865
+
866
+
867
+ @_SpecialForm
868
+ def Concatenate(self, parameters):
869
+ """Special form for annotating higher-order functions.
870
+
871
+ ``Concatenate`` can be used in conjunction with ``ParamSpec`` and
872
+ ``Callable`` to represent a higher-order function which adds, removes or
873
+ transforms the parameters of a callable.
874
+
875
+ For example::
876
+
877
+ Callable[Concatenate[int, P], int]
878
+
879
+ See PEP 612 for detailed information.
880
+ """
881
+ if parameters == ():
882
+ raise TypeError("Cannot take a Concatenate of no types.")
883
+ if not isinstance(parameters, tuple):
884
+ parameters = (parameters,)
885
+ if not (parameters[-1] is ... or isinstance(parameters[-1], ParamSpec)):
886
+ raise TypeError("The last parameter to Concatenate should be a "
887
+ "ParamSpec variable or ellipsis.")
888
+ msg = "Concatenate[arg, ...]: each arg must be a type."
889
+ parameters = (*(_type_check(p, msg) for p in parameters[:-1]), parameters[-1])
890
+ return _ConcatenateGenericAlias(self, parameters)
891
+
892
+
893
+ @_SpecialForm
894
+ def TypeGuard(self, parameters):
895
+ """Special typing construct for marking user-defined type predicate functions.
896
+
897
+ ``TypeGuard`` can be used to annotate the return type of a user-defined
898
+ type predicate function. ``TypeGuard`` only accepts a single type argument.
899
+ At runtime, functions marked this way should return a boolean.
900
+
901
+ ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
902
+ type checkers to determine a more precise type of an expression within a
903
+ program's code flow. Usually type narrowing is done by analyzing
904
+ conditional code flow and applying the narrowing to a block of code. The
905
+ conditional expression here is sometimes referred to as a "type predicate".
906
+
907
+ Sometimes it would be convenient to use a user-defined boolean function
908
+ as a type predicate. Such a function should use ``TypeGuard[...]`` or
909
+ ``TypeIs[...]`` as its return type to alert static type checkers to
910
+ this intention. ``TypeGuard`` should be used over ``TypeIs`` when narrowing
911
+ from an incompatible type (e.g., ``list[object]`` to ``list[int]``) or when
912
+ the function does not return ``True`` for all instances of the narrowed type.
913
+
914
+ Using ``-> TypeGuard[NarrowedType]`` tells the static type checker that
915
+ for a given function:
916
+
917
+ 1. The return value is a boolean.
918
+ 2. If the return value is ``True``, the type of its argument
919
+ is ``NarrowedType``.
920
+
921
+ For example::
922
+
923
+ def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
924
+ '''Determines whether all objects in the list are strings'''
925
+ return all(isinstance(x, str) for x in val)
926
+
927
+ def func1(val: list[object]):
928
+ if is_str_list(val):
929
+ # Type of ``val`` is narrowed to ``list[str]``.
930
+ print(" ".join(val))
931
+ else:
932
+ # Type of ``val`` remains as ``list[object]``.
933
+ print("Not a list of strings!")
934
+
935
+ Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
936
+ form of ``TypeA`` (it can even be a wider form) and this may lead to
937
+ type-unsafe results. The main reason is to allow for things like
938
+ narrowing ``list[object]`` to ``list[str]`` even though the latter is not
939
+ a subtype of the former, since ``list`` is invariant. The responsibility of
940
+ writing type-safe type predicates is left to the user.
941
+
942
+ ``TypeGuard`` also works with type variables. For more information, see
943
+ PEP 647 (User-Defined Type Guards).
944
+ """
945
+ item = _type_check(parameters, f'{self} accepts only single type.')
946
+ return _GenericAlias(self, (item,))
947
+
948
+
949
+ @_SpecialForm
950
+ def TypeIs(self, parameters):
951
+ """Special typing construct for marking user-defined type predicate functions.
952
+
953
+ ``TypeIs`` can be used to annotate the return type of a user-defined
954
+ type predicate function. ``TypeIs`` only accepts a single type argument.
955
+ At runtime, functions marked this way should return a boolean and accept
956
+ at least one argument.
957
+
958
+ ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
959
+ type checkers to determine a more precise type of an expression within a
960
+ program's code flow. Usually type narrowing is done by analyzing
961
+ conditional code flow and applying the narrowing to a block of code. The
962
+ conditional expression here is sometimes referred to as a "type predicate".
963
+
964
+ Sometimes it would be convenient to use a user-defined boolean function
965
+ as a type predicate. Such a function should use ``TypeIs[...]`` or
966
+ ``TypeGuard[...]`` as its return type to alert static type checkers to
967
+ this intention. ``TypeIs`` usually has more intuitive behavior than
968
+ ``TypeGuard``, but it cannot be used when the input and output types
969
+ are incompatible (e.g., ``list[object]`` to ``list[int]``) or when the
970
+ function does not return ``True`` for all instances of the narrowed type.
971
+
972
+ Using ``-> TypeIs[NarrowedType]`` tells the static type checker that for
973
+ a given function:
974
+
975
+ 1. The return value is a boolean.
976
+ 2. If the return value is ``True``, the type of its argument
977
+ is the intersection of the argument's original type and
978
+ ``NarrowedType``.
979
+ 3. If the return value is ``False``, the type of its argument
980
+ is narrowed to exclude ``NarrowedType``.
981
+
982
+ For example::
983
+
984
+ from typing import assert_type, final, TypeIs
985
+
986
+ class Parent: pass
987
+ class Child(Parent): pass
988
+ @final
989
+ class Unrelated: pass
990
+
991
+ def is_parent(val: object) -> TypeIs[Parent]:
992
+ return isinstance(val, Parent)
993
+
994
+ def run(arg: Child | Unrelated):
995
+ if is_parent(arg):
996
+ # Type of ``arg`` is narrowed to the intersection
997
+ # of ``Parent`` and ``Child``, which is equivalent to
998
+ # ``Child``.
999
+ assert_type(arg, Child)
1000
+ else:
1001
+ # Type of ``arg`` is narrowed to exclude ``Parent``,
1002
+ # so only ``Unrelated`` is left.
1003
+ assert_type(arg, Unrelated)
1004
+
1005
+ The type inside ``TypeIs`` must be consistent with the type of the
1006
+ function's argument; if it is not, static type checkers will raise
1007
+ an error. An incorrectly written ``TypeIs`` function can lead to
1008
+ unsound behavior in the type system; it is the user's responsibility
1009
+ to write such functions in a type-safe manner.
1010
+
1011
+ ``TypeIs`` also works with type variables. For more information, see
1012
+ PEP 742 (Narrowing types with ``TypeIs``).
1013
+ """
1014
+ item = _type_check(parameters, f'{self} accepts only single type.')
1015
+ return _GenericAlias(self, (item,))
1016
+
1017
+
1018
+ class ForwardRef(_Final, _root=True):
1019
+ """Internal wrapper to hold a forward reference."""
1020
+
1021
+ __slots__ = ('__forward_arg__', '__forward_code__',
1022
+ '__forward_evaluated__', '__forward_value__',
1023
+ '__forward_is_argument__', '__forward_is_class__',
1024
+ '__forward_module__')
1025
+
1026
+ def __init__(self, arg, is_argument=True, module=None, *, is_class=False):
1027
+ if not isinstance(arg, str):
1028
+ raise TypeError(f"Forward reference must be a string -- got {arg!r}")
1029
+
1030
+ try:
1031
+ code = compile(_rewrite_star_unpack(arg), '<string>', 'eval')
1032
+ except SyntaxError:
1033
+ raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
1034
+
1035
+ self.__forward_arg__ = arg
1036
+ self.__forward_code__ = code
1037
+ self.__forward_evaluated__ = False
1038
+ self.__forward_value__ = None
1039
+ self.__forward_is_argument__ = is_argument
1040
+ self.__forward_is_class__ = is_class
1041
+ self.__forward_module__ = module
1042
+
1043
+ def _evaluate(self, globalns, localns, type_params=_sentinel, *, recursive_guard):
1044
+ if type_params is _sentinel:
1045
+ _deprecation_warning_for_no_type_params_passed("typing.ForwardRef._evaluate")
1046
+ type_params = ()
1047
+ if self.__forward_arg__ in recursive_guard:
1048
+ return self
1049
+ if not self.__forward_evaluated__ or localns is not globalns:
1050
+ if globalns is None and localns is None:
1051
+ globalns = localns = {}
1052
+ elif globalns is None:
1053
+ globalns = localns
1054
+ elif localns is None:
1055
+ localns = globalns
1056
+ if self.__forward_module__ is not None:
1057
+ globalns = getattr(
1058
+ sys.modules.get(self.__forward_module__, None), '__dict__', globalns
1059
+ )
1060
+
1061
+ # type parameters require some special handling,
1062
+ # as they exist in their own scope
1063
+ # but `eval()` does not have a dedicated parameter for that scope.
1064
+ # For classes, names in type parameter scopes should override
1065
+ # names in the global scope (which here are called `localns`!),
1066
+ # but should in turn be overridden by names in the class scope
1067
+ # (which here are called `globalns`!)
1068
+ if type_params:
1069
+ globalns, localns = dict(globalns), dict(localns)
1070
+ for param in type_params:
1071
+ param_name = param.__name__
1072
+ if not self.__forward_is_class__ or param_name not in globalns:
1073
+ globalns[param_name] = param
1074
+ localns.pop(param_name, None)
1075
+
1076
+ type_ = _type_check(
1077
+ eval(self.__forward_code__, globalns, localns),
1078
+ "Forward references must evaluate to types.",
1079
+ is_argument=self.__forward_is_argument__,
1080
+ allow_special_forms=self.__forward_is_class__,
1081
+ )
1082
+ self.__forward_value__ = _eval_type(
1083
+ type_,
1084
+ globalns,
1085
+ localns,
1086
+ type_params,
1087
+ recursive_guard=(recursive_guard | {self.__forward_arg__}),
1088
+ )
1089
+ self.__forward_evaluated__ = True
1090
+ return self.__forward_value__
1091
+
1092
+ def __eq__(self, other):
1093
+ if not isinstance(other, ForwardRef):
1094
+ return NotImplemented
1095
+ if self.__forward_evaluated__ and other.__forward_evaluated__:
1096
+ return (self.__forward_arg__ == other.__forward_arg__ and
1097
+ self.__forward_value__ == other.__forward_value__)
1098
+ return (self.__forward_arg__ == other.__forward_arg__ and
1099
+ self.__forward_module__ == other.__forward_module__)
1100
+
1101
+ def __hash__(self):
1102
+ return hash((self.__forward_arg__, self.__forward_module__))
1103
+
1104
+ def __or__(self, other):
1105
+ return Union[self, other]
1106
+
1107
+ def __ror__(self, other):
1108
+ return Union[other, self]
1109
+
1110
+ def __repr__(self):
1111
+ if self.__forward_module__ is None:
1112
+ module_repr = ''
1113
+ else:
1114
+ module_repr = f', module={self.__forward_module__!r}'
1115
+ return f'ForwardRef({self.__forward_arg__!r}{module_repr})'
1116
+
1117
+
1118
+ def _rewrite_star_unpack(arg):
1119
+ """If the given argument annotation expression is a star unpack e.g. `'*Ts'`
1120
+ rewrite it to a valid expression.
1121
+ """
1122
+ if arg.startswith("*"):
1123
+ return f"({arg},)[0]" # E.g. (*Ts,)[0] or (*tuple[int, int],)[0]
1124
+ else:
1125
+ return arg
1126
+
1127
+
1128
+ def _is_unpacked_typevartuple(x: Any) -> bool:
1129
+ return ((not isinstance(x, type)) and
1130
+ getattr(x, '__typing_is_unpacked_typevartuple__', False))
1131
+
1132
+
1133
+ def _is_typevar_like(x: Any) -> bool:
1134
+ return isinstance(x, (TypeVar, ParamSpec)) or _is_unpacked_typevartuple(x)
1135
+
1136
+
1137
+ def _typevar_subst(self, arg):
1138
+ msg = "Parameters to generic types must be types."
1139
+ arg = _type_check(arg, msg, is_argument=True)
1140
+ if ((isinstance(arg, _GenericAlias) and arg.__origin__ is Unpack) or
1141
+ (isinstance(arg, GenericAlias) and getattr(arg, '__unpacked__', False))):
1142
+ raise TypeError(f"{arg} is not valid as type argument")
1143
+ return arg
1144
+
1145
+
1146
+ def _typevartuple_prepare_subst(self, alias, args):
1147
+ params = alias.__parameters__
1148
+ typevartuple_index = params.index(self)
1149
+ for param in params[typevartuple_index + 1:]:
1150
+ if isinstance(param, TypeVarTuple):
1151
+ raise TypeError(f"More than one TypeVarTuple parameter in {alias}")
1152
+
1153
+ alen = len(args)
1154
+ plen = len(params)
1155
+ left = typevartuple_index
1156
+ right = plen - typevartuple_index - 1
1157
+ var_tuple_index = None
1158
+ fillarg = None
1159
+ for k, arg in enumerate(args):
1160
+ if not isinstance(arg, type):
1161
+ subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
1162
+ if subargs and len(subargs) == 2 and subargs[-1] is ...:
1163
+ if var_tuple_index is not None:
1164
+ raise TypeError("More than one unpacked arbitrary-length tuple argument")
1165
+ var_tuple_index = k
1166
+ fillarg = subargs[0]
1167
+ if var_tuple_index is not None:
1168
+ left = min(left, var_tuple_index)
1169
+ right = min(right, alen - var_tuple_index - 1)
1170
+ elif left + right > alen:
1171
+ raise TypeError(f"Too few arguments for {alias};"
1172
+ f" actual {alen}, expected at least {plen-1}")
1173
+ if left == alen - right and self.has_default():
1174
+ replacement = _unpack_args(self.__default__)
1175
+ else:
1176
+ replacement = args[left: alen - right]
1177
+
1178
+ return (
1179
+ *args[:left],
1180
+ *([fillarg]*(typevartuple_index - left)),
1181
+ replacement,
1182
+ *([fillarg]*(plen - right - left - typevartuple_index - 1)),
1183
+ *args[alen - right:],
1184
+ )
1185
+
1186
+
1187
+ def _paramspec_subst(self, arg):
1188
+ if isinstance(arg, (list, tuple)):
1189
+ arg = tuple(_type_check(a, "Expected a type.") for a in arg)
1190
+ elif not _is_param_expr(arg):
1191
+ raise TypeError(f"Expected a list of types, an ellipsis, "
1192
+ f"ParamSpec, or Concatenate. Got {arg}")
1193
+ return arg
1194
+
1195
+
1196
+ def _paramspec_prepare_subst(self, alias, args):
1197
+ params = alias.__parameters__
1198
+ i = params.index(self)
1199
+ if i == len(args) and self.has_default():
1200
+ args = (*args, self.__default__)
1201
+ if i >= len(args):
1202
+ raise TypeError(f"Too few arguments for {alias}")
1203
+ # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612.
1204
+ if len(params) == 1 and not _is_param_expr(args[0]):
1205
+ assert i == 0
1206
+ args = (args,)
1207
+ # Convert lists to tuples to help other libraries cache the results.
1208
+ elif isinstance(args[i], list):
1209
+ args = (*args[:i], tuple(args[i]), *args[i+1:])
1210
+ return args
1211
+
1212
+
1213
+ @_tp_cache
1214
+ def _generic_class_getitem(cls, args):
1215
+ """Parameterizes a generic class.
1216
+
1217
+ At least, parameterizing a generic class is the *main* thing this method
1218
+ does. For example, for some generic class `Foo`, this is called when we
1219
+ do `Foo[int]` - there, with `cls=Foo` and `args=int`.
1220
+
1221
+ However, note that this method is also called when defining generic
1222
+ classes in the first place with `class Foo(Generic[T]): ...`.
1223
+ """
1224
+ if not isinstance(args, tuple):
1225
+ args = (args,)
1226
+
1227
+ args = tuple(_type_convert(p) for p in args)
1228
+ is_generic_or_protocol = cls in (Generic, Protocol)
1229
+
1230
+ if is_generic_or_protocol:
1231
+ # Generic and Protocol can only be subscripted with unique type variables.
1232
+ if not args:
1233
+ raise TypeError(
1234
+ f"Parameter list to {cls.__qualname__}[...] cannot be empty"
1235
+ )
1236
+ if not all(_is_typevar_like(p) for p in args):
1237
+ raise TypeError(
1238
+ f"Parameters to {cls.__name__}[...] must all be type variables "
1239
+ f"or parameter specification variables.")
1240
+ if len(set(args)) != len(args):
1241
+ raise TypeError(
1242
+ f"Parameters to {cls.__name__}[...] must all be unique")
1243
+ else:
1244
+ # Subscripting a regular Generic subclass.
1245
+ try:
1246
+ parameters = cls.__parameters__
1247
+ except AttributeError as e:
1248
+ init_subclass = getattr(cls, '__init_subclass__', None)
1249
+ if init_subclass not in {None, Generic.__init_subclass__}:
1250
+ e.add_note(
1251
+ f"Note: this exception may have been caused by "
1252
+ f"{init_subclass.__qualname__!r} (or the "
1253
+ f"'__init_subclass__' method on a superclass) not "
1254
+ f"calling 'super().__init_subclass__()'"
1255
+ )
1256
+ raise
1257
+ for param in parameters:
1258
+ prepare = getattr(param, '__typing_prepare_subst__', None)
1259
+ if prepare is not None:
1260
+ args = prepare(cls, args)
1261
+ _check_generic_specialization(cls, args)
1262
+
1263
+ new_args = []
1264
+ for param, new_arg in zip(parameters, args):
1265
+ if isinstance(param, TypeVarTuple):
1266
+ new_args.extend(new_arg)
1267
+ else:
1268
+ new_args.append(new_arg)
1269
+ args = tuple(new_args)
1270
+
1271
+ return _GenericAlias(cls, args)
1272
+
1273
+
1274
+ def _generic_init_subclass(cls, *args, **kwargs):
1275
+ super(Generic, cls).__init_subclass__(*args, **kwargs)
1276
+ tvars = []
1277
+ if '__orig_bases__' in cls.__dict__:
1278
+ error = Generic in cls.__orig_bases__
1279
+ else:
1280
+ error = (Generic in cls.__bases__ and
1281
+ cls.__name__ != 'Protocol' and
1282
+ type(cls) != _TypedDictMeta)
1283
+ if error:
1284
+ raise TypeError("Cannot inherit from plain Generic")
1285
+ if '__orig_bases__' in cls.__dict__:
1286
+ tvars = _collect_type_parameters(cls.__orig_bases__)
1287
+ # Look for Generic[T1, ..., Tn].
1288
+ # If found, tvars must be a subset of it.
1289
+ # If not found, tvars is it.
1290
+ # Also check for and reject plain Generic,
1291
+ # and reject multiple Generic[...].
1292
+ gvars = None
1293
+ for base in cls.__orig_bases__:
1294
+ if (isinstance(base, _GenericAlias) and
1295
+ base.__origin__ is Generic):
1296
+ if gvars is not None:
1297
+ raise TypeError(
1298
+ "Cannot inherit from Generic[...] multiple times.")
1299
+ gvars = base.__parameters__
1300
+ if gvars is not None:
1301
+ tvarset = set(tvars)
1302
+ gvarset = set(gvars)
1303
+ if not tvarset <= gvarset:
1304
+ s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
1305
+ s_args = ', '.join(str(g) for g in gvars)
1306
+ raise TypeError(f"Some type variables ({s_vars}) are"
1307
+ f" not listed in Generic[{s_args}]")
1308
+ tvars = gvars
1309
+ cls.__parameters__ = tuple(tvars)
1310
+
1311
+
1312
+ def _is_dunder(attr):
1313
+ return attr.startswith('__') and attr.endswith('__')
1314
+
1315
+ class _BaseGenericAlias(_Final, _root=True):
1316
+ """The central part of the internal API.
1317
+
1318
+ This represents a generic version of type 'origin' with type arguments 'params'.
1319
+ There are two kind of these aliases: user defined and special. The special ones
1320
+ are wrappers around builtin collections and ABCs in collections.abc. These must
1321
+ have 'name' always set. If 'inst' is False, then the alias can't be instantiated;
1322
+ this is used by e.g. typing.List and typing.Dict.
1323
+ """
1324
+
1325
+ def __init__(self, origin, *, inst=True, name=None):
1326
+ self._inst = inst
1327
+ self._name = name
1328
+ self.__origin__ = origin
1329
+ self.__slots__ = None # This is not documented.
1330
+
1331
+ def __call__(self, *args, **kwargs):
1332
+ if not self._inst:
1333
+ raise TypeError(f"Type {self._name} cannot be instantiated; "
1334
+ f"use {self.__origin__.__name__}() instead")
1335
+ result = self.__origin__(*args, **kwargs)
1336
+ try:
1337
+ result.__orig_class__ = self
1338
+ # Some objects raise TypeError (or something even more exotic)
1339
+ # if you try to set attributes on them; we guard against that here
1340
+ except Exception:
1341
+ pass
1342
+ return result
1343
+
1344
+ def __mro_entries__(self, bases):
1345
+ res = []
1346
+ if self.__origin__ not in bases:
1347
+ res.append(self.__origin__)
1348
+
1349
+ # Check if any base that occurs after us in `bases` is either itself a
1350
+ # subclass of Generic, or something which will add a subclass of Generic
1351
+ # to `__bases__` via its `__mro_entries__`. If not, add Generic
1352
+ # ourselves. The goal is to ensure that Generic (or a subclass) will
1353
+ # appear exactly once in the final bases tuple. If we let it appear
1354
+ # multiple times, we risk "can't form a consistent MRO" errors.
1355
+ i = bases.index(self)
1356
+ for b in bases[i+1:]:
1357
+ if isinstance(b, _BaseGenericAlias):
1358
+ break
1359
+ if not isinstance(b, type):
1360
+ meth = getattr(b, "__mro_entries__", None)
1361
+ new_bases = meth(bases) if meth else None
1362
+ if (
1363
+ isinstance(new_bases, tuple) and
1364
+ any(
1365
+ isinstance(b2, type) and issubclass(b2, Generic)
1366
+ for b2 in new_bases
1367
+ )
1368
+ ):
1369
+ break
1370
+ elif issubclass(b, Generic):
1371
+ break
1372
+ else:
1373
+ res.append(Generic)
1374
+ return tuple(res)
1375
+
1376
+ def __getattr__(self, attr):
1377
+ if attr in {'__name__', '__qualname__'}:
1378
+ return self._name or self.__origin__.__name__
1379
+
1380
+ # We are careful for copy and pickle.
1381
+ # Also for simplicity we don't relay any dunder names
1382
+ if '__origin__' in self.__dict__ and not _is_dunder(attr):
1383
+ return getattr(self.__origin__, attr)
1384
+ raise AttributeError(attr)
1385
+
1386
+ def __setattr__(self, attr, val):
1387
+ if _is_dunder(attr) or attr in {'_name', '_inst', '_nparams', '_defaults'}:
1388
+ super().__setattr__(attr, val)
1389
+ else:
1390
+ setattr(self.__origin__, attr, val)
1391
+
1392
+ def __instancecheck__(self, obj):
1393
+ return self.__subclasscheck__(type(obj))
1394
+
1395
+ def __subclasscheck__(self, cls):
1396
+ raise TypeError("Subscripted generics cannot be used with"
1397
+ " class and instance checks")
1398
+
1399
+ def __dir__(self):
1400
+ return list(set(super().__dir__()
1401
+ + [attr for attr in dir(self.__origin__) if not _is_dunder(attr)]))
1402
+
1403
+
1404
+ # Special typing constructs Union, Optional, Generic, Callable and Tuple
1405
+ # use three special attributes for internal bookkeeping of generic types:
1406
+ # * __parameters__ is a tuple of unique free type parameters of a generic
1407
+ # type, for example, Dict[T, T].__parameters__ == (T,);
1408
+ # * __origin__ keeps a reference to a type that was subscripted,
1409
+ # e.g., Union[T, int].__origin__ == Union, or the non-generic version of
1410
+ # the type.
1411
+ # * __args__ is a tuple of all arguments used in subscripting,
1412
+ # e.g., Dict[T, int].__args__ == (T, int).
1413
+
1414
+
1415
+ class _GenericAlias(_BaseGenericAlias, _root=True):
1416
+ """The type of parameterized generics.
1417
+
1418
+ That is, for example, `type(List[int])` is `_GenericAlias`.
1419
+
1420
+ Objects which are instances of this class include:
1421
+ * Parameterized container types, e.g. `Tuple[int]`, `List[int]`.
1422
+ * Note that native container types, e.g. `tuple`, `list`, use
1423
+ `types.GenericAlias` instead.
1424
+ * Parameterized classes:
1425
+ class C[T]: pass
1426
+ # C[int] is a _GenericAlias
1427
+ * `Callable` aliases, generic `Callable` aliases, and
1428
+ parameterized `Callable` aliases:
1429
+ T = TypeVar('T')
1430
+ # _CallableGenericAlias inherits from _GenericAlias.
1431
+ A = Callable[[], None] # _CallableGenericAlias
1432
+ B = Callable[[T], None] # _CallableGenericAlias
1433
+ C = B[int] # _CallableGenericAlias
1434
+ * Parameterized `Final`, `ClassVar`, `TypeForm`, `TypeGuard`, and `TypeIs`:
1435
+ # All _GenericAlias
1436
+ Final[int]
1437
+ ClassVar[float]
1438
+ TypeForm[bytearray]
1439
+ TypeGuard[bool]
1440
+ TypeIs[range]
1441
+
1442
+ Note that instances of this class are not classes (e.g by `inspect.isclass`),
1443
+ even though they behave like them.
1444
+ """
1445
+ def __init__(self, origin, args, *, inst=True, name=None):
1446
+ super().__init__(origin, inst=inst, name=name)
1447
+ if not isinstance(args, tuple):
1448
+ args = (args,)
1449
+ self.__args__ = tuple(... if a is _TypingEllipsis else
1450
+ a for a in args)
1451
+ enforce_default_ordering = origin in (Generic, Protocol)
1452
+ self.__parameters__ = _collect_type_parameters(
1453
+ args,
1454
+ enforce_default_ordering=enforce_default_ordering,
1455
+ )
1456
+ if not name:
1457
+ self.__module__ = origin.__module__
1458
+
1459
+ def __eq__(self, other):
1460
+ if not isinstance(other, _GenericAlias):
1461
+ return NotImplemented
1462
+ return (self.__origin__ == other.__origin__
1463
+ and self.__args__ == other.__args__)
1464
+
1465
+ def __hash__(self):
1466
+ return hash((self.__origin__, self.__args__))
1467
+
1468
+ def __or__(self, right):
1469
+ return Union[self, right]
1470
+
1471
+ def __ror__(self, left):
1472
+ return Union[left, self]
1473
+
1474
+ @_tp_cache
1475
+ def __getitem__(self, args):
1476
+ """Parameterizes an already-parameterized object.
1477
+
1478
+ For example, we arrive here doing something like:
1479
+ T1 = TypeVar('T1')
1480
+ T2 = TypeVar('T2')
1481
+ T3 = TypeVar('T3')
1482
+ class A(Generic[T1]): pass
1483
+ B = A[T2] # B is a _GenericAlias
1484
+ C = B[T3] # Invokes _GenericAlias.__getitem__
1485
+
1486
+ We also arrive here when parameterizing a generic `Callable` alias:
1487
+ T = TypeVar('T')
1488
+ C = Callable[[T], None]
1489
+ C[int] # Invokes _GenericAlias.__getitem__
1490
+ """
1491
+
1492
+ if self.__origin__ in (Generic, Protocol):
1493
+ # Can't subscript Generic[...] or Protocol[...].
1494
+ raise TypeError(f"Cannot subscript already-subscripted {self}")
1495
+ if not self.__parameters__:
1496
+ raise TypeError(f"{self} is not a generic class")
1497
+
1498
+ # Preprocess `args`.
1499
+ if not isinstance(args, tuple):
1500
+ args = (args,)
1501
+ args = _unpack_args(*(_type_convert(p) for p in args))
1502
+ new_args = self._determine_new_args(args)
1503
+ r = self.copy_with(new_args)
1504
+ return r
1505
+
1506
+ def _determine_new_args(self, args):
1507
+ """Determines new __args__ for __getitem__.
1508
+
1509
+ For example, suppose we had:
1510
+ T1 = TypeVar('T1')
1511
+ T2 = TypeVar('T2')
1512
+ class A(Generic[T1, T2]): pass
1513
+ T3 = TypeVar('T3')
1514
+ B = A[int, T3]
1515
+ C = B[str]
1516
+ `B.__args__` is `(int, T3)`, so `C.__args__` should be `(int, str)`.
1517
+ Unfortunately, this is harder than it looks, because if `T3` is
1518
+ anything more exotic than a plain `TypeVar`, we need to consider
1519
+ edge cases.
1520
+ """
1521
+ params = self.__parameters__
1522
+ # In the example above, this would be {T3: str}
1523
+ for param in params:
1524
+ prepare = getattr(param, '__typing_prepare_subst__', None)
1525
+ if prepare is not None:
1526
+ args = prepare(self, args)
1527
+ alen = len(args)
1528
+ plen = len(params)
1529
+ if alen != plen:
1530
+ raise TypeError(f"Too {'many' if alen > plen else 'few'} arguments for {self};"
1531
+ f" actual {alen}, expected {plen}")
1532
+ new_arg_by_param = dict(zip(params, args))
1533
+ return tuple(self._make_substitution(self.__args__, new_arg_by_param))
1534
+
1535
+ def _make_substitution(self, args, new_arg_by_param):
1536
+ """Create a list of new type arguments."""
1537
+ new_args = []
1538
+ for old_arg in args:
1539
+ if isinstance(old_arg, type):
1540
+ new_args.append(old_arg)
1541
+ continue
1542
+
1543
+ substfunc = getattr(old_arg, '__typing_subst__', None)
1544
+ if substfunc:
1545
+ new_arg = substfunc(new_arg_by_param[old_arg])
1546
+ else:
1547
+ subparams = getattr(old_arg, '__parameters__', ())
1548
+ if not subparams:
1549
+ new_arg = old_arg
1550
+ else:
1551
+ subargs = []
1552
+ for x in subparams:
1553
+ if isinstance(x, TypeVarTuple):
1554
+ subargs.extend(new_arg_by_param[x])
1555
+ else:
1556
+ subargs.append(new_arg_by_param[x])
1557
+ new_arg = old_arg[tuple(subargs)]
1558
+
1559
+ if self.__origin__ == collections.abc.Callable and isinstance(new_arg, tuple):
1560
+ # Consider the following `Callable`.
1561
+ # C = Callable[[int], str]
1562
+ # Here, `C.__args__` should be (int, str) - NOT ([int], str).
1563
+ # That means that if we had something like...
1564
+ # P = ParamSpec('P')
1565
+ # T = TypeVar('T')
1566
+ # C = Callable[P, T]
1567
+ # D = C[[int, str], float]
1568
+ # ...we need to be careful; `new_args` should end up as
1569
+ # `(int, str, float)` rather than `([int, str], float)`.
1570
+ new_args.extend(new_arg)
1571
+ elif _is_unpacked_typevartuple(old_arg):
1572
+ # Consider the following `_GenericAlias`, `B`:
1573
+ # class A(Generic[*Ts]): ...
1574
+ # B = A[T, *Ts]
1575
+ # If we then do:
1576
+ # B[float, int, str]
1577
+ # The `new_arg` corresponding to `T` will be `float`, and the
1578
+ # `new_arg` corresponding to `*Ts` will be `(int, str)`. We
1579
+ # should join all these types together in a flat list
1580
+ # `(float, int, str)` - so again, we should `extend`.
1581
+ new_args.extend(new_arg)
1582
+ elif isinstance(old_arg, tuple):
1583
+ # Corner case:
1584
+ # P = ParamSpec('P')
1585
+ # T = TypeVar('T')
1586
+ # class Base(Generic[P]): ...
1587
+ # Can be substituted like this:
1588
+ # X = Base[[int, T]]
1589
+ # In this case, `old_arg` will be a tuple:
1590
+ new_args.append(
1591
+ tuple(self._make_substitution(old_arg, new_arg_by_param)),
1592
+ )
1593
+ else:
1594
+ new_args.append(new_arg)
1595
+ return new_args
1596
+
1597
+ def copy_with(self, args):
1598
+ return self.__class__(self.__origin__, args, name=self._name, inst=self._inst)
1599
+
1600
+ def __repr__(self):
1601
+ if self._name:
1602
+ name = 'typing.' + self._name
1603
+ else:
1604
+ name = _type_repr(self.__origin__)
1605
+ if self.__args__:
1606
+ args = ", ".join([_type_repr(a) for a in self.__args__])
1607
+ else:
1608
+ # To ensure the repr is eval-able.
1609
+ args = "()"
1610
+ return f'{name}[{args}]'
1611
+
1612
+ def __reduce__(self):
1613
+ if self._name:
1614
+ origin = globals()[self._name]
1615
+ else:
1616
+ origin = self.__origin__
1617
+ args = tuple(self.__args__)
1618
+ if len(args) == 1 and not isinstance(args[0], tuple):
1619
+ args, = args
1620
+ return operator.getitem, (origin, args)
1621
+
1622
+ def __mro_entries__(self, bases):
1623
+ if isinstance(self.__origin__, _SpecialForm):
1624
+ raise TypeError(f"Cannot subclass {self!r}")
1625
+
1626
+ if self._name: # generic version of an ABC or built-in class
1627
+ return super().__mro_entries__(bases)
1628
+ if self.__origin__ is Generic:
1629
+ if Protocol in bases:
1630
+ return ()
1631
+ i = bases.index(self)
1632
+ for b in bases[i+1:]:
1633
+ if isinstance(b, _BaseGenericAlias) and b is not self:
1634
+ return ()
1635
+ return (self.__origin__,)
1636
+
1637
+ def __iter__(self):
1638
+ yield Unpack[self]
1639
+
1640
+
1641
+ # _nparams is the number of accepted parameters, e.g. 0 for Hashable,
1642
+ # 1 for List and 2 for Dict. It may be -1 if variable number of
1643
+ # parameters are accepted (needs custom __getitem__).
1644
+
1645
+ class _SpecialGenericAlias(_NotIterable, _BaseGenericAlias, _root=True):
1646
+ def __init__(self, origin, nparams, *, inst=True, name=None, defaults=()):
1647
+ if name is None:
1648
+ name = origin.__name__
1649
+ super().__init__(origin, inst=inst, name=name)
1650
+ self._nparams = nparams
1651
+ self._defaults = defaults
1652
+ if origin.__module__ == 'builtins':
1653
+ self.__doc__ = f'Deprecated alias to {origin.__qualname__}.'
1654
+ else:
1655
+ self.__doc__ = f'Deprecated alias to {origin.__module__}.{origin.__qualname__}.'
1656
+
1657
+ @_tp_cache
1658
+ def __getitem__(self, params):
1659
+ if not isinstance(params, tuple):
1660
+ params = (params,)
1661
+ msg = "Parameters to generic types must be types."
1662
+ params = tuple(_type_check(p, msg) for p in params)
1663
+ if (self._defaults
1664
+ and len(params) < self._nparams
1665
+ and len(params) + len(self._defaults) >= self._nparams
1666
+ ):
1667
+ params = (*params, *self._defaults[len(params) - self._nparams:])
1668
+ actual_len = len(params)
1669
+
1670
+ if actual_len != self._nparams:
1671
+ if self._defaults:
1672
+ expected = f"at least {self._nparams - len(self._defaults)}"
1673
+ else:
1674
+ expected = str(self._nparams)
1675
+ if not self._nparams:
1676
+ raise TypeError(f"{self} is not a generic class")
1677
+ raise TypeError(f"Too {'many' if actual_len > self._nparams else 'few'} arguments for {self};"
1678
+ f" actual {actual_len}, expected {expected}")
1679
+ return self.copy_with(params)
1680
+
1681
+ def copy_with(self, params):
1682
+ return _GenericAlias(self.__origin__, params,
1683
+ name=self._name, inst=self._inst)
1684
+
1685
+ def __repr__(self):
1686
+ return 'typing.' + self._name
1687
+
1688
+ def __subclasscheck__(self, cls):
1689
+ if isinstance(cls, _SpecialGenericAlias):
1690
+ return issubclass(cls.__origin__, self.__origin__)
1691
+ if not isinstance(cls, _GenericAlias):
1692
+ return issubclass(cls, self.__origin__)
1693
+ return super().__subclasscheck__(cls)
1694
+
1695
+ def __reduce__(self):
1696
+ return self._name
1697
+
1698
+ def __or__(self, right):
1699
+ return Union[self, right]
1700
+
1701
+ def __ror__(self, left):
1702
+ return Union[left, self]
1703
+
1704
+
1705
+ class _DeprecatedGenericAlias(_SpecialGenericAlias, _root=True):
1706
+ def __init__(
1707
+ self, origin, nparams, *, removal_version, inst=True, name=None
1708
+ ):
1709
+ super().__init__(origin, nparams, inst=inst, name=name)
1710
+ self._removal_version = removal_version
1711
+
1712
+ def __instancecheck__(self, inst):
1713
+ import warnings
1714
+ warnings._deprecated(
1715
+ f"{self.__module__}.{self._name}", remove=self._removal_version
1716
+ )
1717
+ return super().__instancecheck__(inst)
1718
+
1719
+
1720
+ class _CallableGenericAlias(_NotIterable, _GenericAlias, _root=True):
1721
+ def __repr__(self):
1722
+ assert self._name == 'Callable'
1723
+ args = self.__args__
1724
+ if len(args) == 2 and _is_param_expr(args[0]):
1725
+ return super().__repr__()
1726
+ return (f'typing.Callable'
1727
+ f'[[{", ".join([_type_repr(a) for a in args[:-1]])}], '
1728
+ f'{_type_repr(args[-1])}]')
1729
+
1730
+ def __reduce__(self):
1731
+ args = self.__args__
1732
+ if not (len(args) == 2 and _is_param_expr(args[0])):
1733
+ args = list(args[:-1]), args[-1]
1734
+ return operator.getitem, (Callable, args)
1735
+
1736
+
1737
+ class _CallableType(_SpecialGenericAlias, _root=True):
1738
+ def copy_with(self, params):
1739
+ return _CallableGenericAlias(self.__origin__, params,
1740
+ name=self._name, inst=self._inst)
1741
+
1742
+ def __getitem__(self, params):
1743
+ if not isinstance(params, tuple) or len(params) != 2:
1744
+ raise TypeError("Callable must be used as "
1745
+ "Callable[[arg, ...], result].")
1746
+ args, result = params
1747
+ # This relaxes what args can be on purpose to allow things like
1748
+ # PEP 612 ParamSpec. Responsibility for whether a user is using
1749
+ # Callable[...] properly is deferred to static type checkers.
1750
+ if isinstance(args, list):
1751
+ params = (tuple(args), result)
1752
+ else:
1753
+ params = (args, result)
1754
+ return self.__getitem_inner__(params)
1755
+
1756
+ @_tp_cache
1757
+ def __getitem_inner__(self, params):
1758
+ args, result = params
1759
+ msg = "Callable[args, result]: result must be a type."
1760
+ result = _type_check(result, msg)
1761
+ if args is Ellipsis:
1762
+ return self.copy_with((_TypingEllipsis, result))
1763
+ if not isinstance(args, tuple):
1764
+ args = (args,)
1765
+ args = tuple(_type_convert(arg) for arg in args)
1766
+ params = args + (result,)
1767
+ return self.copy_with(params)
1768
+
1769
+
1770
+ class _TupleType(_SpecialGenericAlias, _root=True):
1771
+ @_tp_cache
1772
+ def __getitem__(self, params):
1773
+ if not isinstance(params, tuple):
1774
+ params = (params,)
1775
+ if len(params) >= 2 and params[-1] is ...:
1776
+ msg = "Tuple[t, ...]: t must be a type."
1777
+ params = tuple(_type_check(p, msg) for p in params[:-1])
1778
+ return self.copy_with((*params, _TypingEllipsis))
1779
+ msg = "Tuple[t0, t1, ...]: each t must be a type."
1780
+ params = tuple(_type_check(p, msg) for p in params)
1781
+ return self.copy_with(params)
1782
+
1783
+
1784
+ class _UnionGenericAlias(_NotIterable, _GenericAlias, _root=True):
1785
+ def copy_with(self, params):
1786
+ return Union[params]
1787
+
1788
+ def __eq__(self, other):
1789
+ if not isinstance(other, (_UnionGenericAlias, types.UnionType)):
1790
+ return NotImplemented
1791
+ try: # fast path
1792
+ return set(self.__args__) == set(other.__args__)
1793
+ except TypeError: # not hashable, slow path
1794
+ return _compare_args_orderless(self.__args__, other.__args__)
1795
+
1796
+ def __hash__(self):
1797
+ return hash(frozenset(self.__args__))
1798
+
1799
+ def __repr__(self):
1800
+ args = self.__args__
1801
+ if len(args) == 2:
1802
+ if args[0] is type(None):
1803
+ return f'typing.Optional[{_type_repr(args[1])}]'
1804
+ elif args[1] is type(None):
1805
+ return f'typing.Optional[{_type_repr(args[0])}]'
1806
+ return super().__repr__()
1807
+
1808
+ def __instancecheck__(self, obj):
1809
+ for arg in self.__args__:
1810
+ if isinstance(obj, arg):
1811
+ return True
1812
+ return False
1813
+
1814
+ def __subclasscheck__(self, cls):
1815
+ for arg in self.__args__:
1816
+ if issubclass(cls, arg):
1817
+ return True
1818
+ return False
1819
+
1820
+ def __reduce__(self):
1821
+ func, (origin, args) = super().__reduce__()
1822
+ return func, (Union, args)
1823
+
1824
+
1825
+ def _value_and_type_iter(parameters):
1826
+ return ((p, type(p)) for p in parameters)
1827
+
1828
+
1829
+ class _LiteralGenericAlias(_GenericAlias, _root=True):
1830
+ def __eq__(self, other):
1831
+ if not isinstance(other, _LiteralGenericAlias):
1832
+ return NotImplemented
1833
+
1834
+ return set(_value_and_type_iter(self.__args__)) == set(_value_and_type_iter(other.__args__))
1835
+
1836
+ def __hash__(self):
1837
+ return hash(frozenset(_value_and_type_iter(self.__args__)))
1838
+
1839
+
1840
+ class _ConcatenateGenericAlias(_GenericAlias, _root=True):
1841
+ def copy_with(self, params):
1842
+ if isinstance(params[-1], (list, tuple)):
1843
+ return (*params[:-1], *params[-1])
1844
+ if isinstance(params[-1], _ConcatenateGenericAlias):
1845
+ params = (*params[:-1], *params[-1].__args__)
1846
+ return super().copy_with(params)
1847
+
1848
+
1849
+ @_SpecialForm
1850
+ def Unpack(self, parameters):
1851
+ """Type unpack operator.
1852
+
1853
+ The type unpack operator takes the child types from some container type,
1854
+ such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'.
1855
+
1856
+ For example::
1857
+
1858
+ # For some generic class `Foo`:
1859
+ Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
1860
+
1861
+ Ts = TypeVarTuple('Ts')
1862
+ # Specifies that `Bar` is generic in an arbitrary number of types.
1863
+ # (Think of `Ts` as a tuple of an arbitrary number of individual
1864
+ # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
1865
+ # `Generic[]`.)
1866
+ class Bar(Generic[Unpack[Ts]]): ...
1867
+ Bar[int] # Valid
1868
+ Bar[int, str] # Also valid
1869
+
1870
+ From Python 3.11, this can also be done using the `*` operator::
1871
+
1872
+ Foo[*tuple[int, str]]
1873
+ class Bar(Generic[*Ts]): ...
1874
+
1875
+ And from Python 3.12, it can be done using built-in syntax for generics::
1876
+
1877
+ Foo[*tuple[int, str]]
1878
+ class Bar[*Ts]: ...
1879
+
1880
+ The operator can also be used along with a `TypedDict` to annotate
1881
+ `**kwargs` in a function signature::
1882
+
1883
+ class Movie(TypedDict):
1884
+ name: str
1885
+ year: int
1886
+
1887
+ # This function expects two keyword arguments - *name* of type `str` and
1888
+ # *year* of type `int`.
1889
+ def foo(**kwargs: Unpack[Movie]): ...
1890
+
1891
+ Note that there is only some runtime checking of this operator. Not
1892
+ everything the runtime allows is accepted by static type checkers.
1893
+
1894
+ For more information, see PEPs 646 and 692.
1895
+ """
1896
+ item = _type_check(parameters, f'{self} accepts only single type.')
1897
+ return _UnpackGenericAlias(origin=self, args=(item,))
1898
+
1899
+
1900
+ class _UnpackGenericAlias(_GenericAlias, _root=True):
1901
+ def __repr__(self):
1902
+ # `Unpack` only takes one argument, so __args__ should contain only
1903
+ # a single item.
1904
+ return f'typing.Unpack[{_type_repr(self.__args__[0])}]'
1905
+
1906
+ def __getitem__(self, args):
1907
+ if self.__typing_is_unpacked_typevartuple__:
1908
+ return args
1909
+ return super().__getitem__(args)
1910
+
1911
+ @property
1912
+ def __typing_unpacked_tuple_args__(self):
1913
+ assert self.__origin__ is Unpack
1914
+ assert len(self.__args__) == 1
1915
+ arg, = self.__args__
1916
+ if isinstance(arg, (_GenericAlias, types.GenericAlias)):
1917
+ if arg.__origin__ is not tuple:
1918
+ raise TypeError("Unpack[...] must be used with a tuple type")
1919
+ return arg.__args__
1920
+ return None
1921
+
1922
+ @property
1923
+ def __typing_is_unpacked_typevartuple__(self):
1924
+ assert self.__origin__ is Unpack
1925
+ assert len(self.__args__) == 1
1926
+ return isinstance(self.__args__[0], TypeVarTuple)
1927
+
1928
+
1929
+ class _TypingEllipsis:
1930
+ """Internal placeholder for ... (ellipsis)."""
1931
+
1932
+
1933
+ _TYPING_INTERNALS = frozenset({
1934
+ '__parameters__', '__orig_bases__', '__orig_class__',
1935
+ '_is_protocol', '_is_runtime_protocol', '__protocol_attrs__',
1936
+ '__non_callable_proto_members__', '__type_params__',
1937
+ })
1938
+
1939
+ _SPECIAL_NAMES = frozenset({
1940
+ '__abstractmethods__', '__annotations__', '__dict__', '__doc__',
1941
+ '__init__', '__module__', '__new__', '__slots__',
1942
+ '__subclasshook__', '__weakref__', '__class_getitem__',
1943
+ '__match_args__', '__static_attributes__', '__firstlineno__',
1944
+ })
1945
+
1946
+ # These special attributes will be not collected as protocol members.
1947
+ EXCLUDED_ATTRIBUTES = _TYPING_INTERNALS | _SPECIAL_NAMES | {'_MutableMapping__marker'}
1948
+
1949
+
1950
+ def _get_protocol_attrs(cls):
1951
+ """Collect protocol members from a protocol class objects.
1952
+
1953
+ This includes names actually defined in the class dictionary, as well
1954
+ as names that appear in annotations. Special names (above) are skipped.
1955
+ """
1956
+ attrs = set()
1957
+ for base in cls.__mro__[:-1]: # without object
1958
+ if base.__name__ in {'Protocol', 'Generic'}:
1959
+ continue
1960
+ annotations = getattr(base, '__annotations__', {})
1961
+ for attr in (*base.__dict__, *annotations):
1962
+ if not attr.startswith('_abc_') and attr not in EXCLUDED_ATTRIBUTES:
1963
+ attrs.add(attr)
1964
+ return attrs
1965
+
1966
+
1967
+ def _no_init_or_replace_init(self, *args, **kwargs):
1968
+ cls = type(self)
1969
+
1970
+ if cls._is_protocol:
1971
+ raise TypeError('Protocols cannot be instantiated')
1972
+
1973
+ # Already using a custom `__init__`. No need to calculate correct
1974
+ # `__init__` to call. This can lead to RecursionError. See bpo-45121.
1975
+ if cls.__init__ is not _no_init_or_replace_init:
1976
+ return
1977
+
1978
+ # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.
1979
+ # The first instantiation of the subclass will call `_no_init_or_replace_init` which
1980
+ # searches for a proper new `__init__` in the MRO. The new `__init__`
1981
+ # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent
1982
+ # instantiation of the protocol subclass will thus use the new
1983
+ # `__init__` and no longer call `_no_init_or_replace_init`.
1984
+ for base in cls.__mro__:
1985
+ init = base.__dict__.get('__init__', _no_init_or_replace_init)
1986
+ if init is not _no_init_or_replace_init:
1987
+ cls.__init__ = init
1988
+ break
1989
+ else:
1990
+ # should not happen
1991
+ cls.__init__ = object.__init__
1992
+
1993
+ cls.__init__(self, *args, **kwargs)
1994
+
1995
+
1996
+ def _caller(depth=1, default='__main__'):
1997
+ try:
1998
+ return sys._getframemodulename(depth + 1) or default
1999
+ except AttributeError: # For platforms without _getframemodulename()
2000
+ pass
2001
+ try:
2002
+ return sys._getframe(depth + 1).f_globals.get('__name__', default)
2003
+ except (AttributeError, ValueError): # For platforms without _getframe()
2004
+ pass
2005
+ return None
2006
+
2007
+ def _allow_reckless_class_checks(depth=2):
2008
+ """Allow instance and class checks for special stdlib modules.
2009
+
2010
+ The abc and functools modules indiscriminately call isinstance() and
2011
+ issubclass() on the whole MRO of a user class, which may contain protocols.
2012
+ """
2013
+ return _caller(depth) in {'abc', 'functools', None}
2014
+
2015
+
2016
+ _PROTO_ALLOWLIST = {
2017
+ 'collections.abc': [
2018
+ 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
2019
+ 'AsyncIterator', 'Hashable', 'Sized', 'Container', 'Collection',
2020
+ 'Reversible', 'Buffer',
2021
+ ],
2022
+ 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
2023
+ }
2024
+
2025
+
2026
+ @functools.cache
2027
+ def _lazy_load_getattr_static():
2028
+ # Import getattr_static lazily so as not to slow down the import of typing.py
2029
+ # Cache the result so we don't slow down _ProtocolMeta.__instancecheck__ unnecessarily
2030
+ from inspect import getattr_static
2031
+ return getattr_static
2032
+
2033
+
2034
+ _cleanups.append(_lazy_load_getattr_static.cache_clear)
2035
+
2036
+ def _pickle_psargs(psargs):
2037
+ return ParamSpecArgs, (psargs.__origin__,)
2038
+
2039
+ copyreg.pickle(ParamSpecArgs, _pickle_psargs)
2040
+
2041
+ def _pickle_pskwargs(pskwargs):
2042
+ return ParamSpecKwargs, (pskwargs.__origin__,)
2043
+
2044
+ copyreg.pickle(ParamSpecKwargs, _pickle_pskwargs)
2045
+
2046
+ del _pickle_psargs, _pickle_pskwargs
2047
+
2048
+
2049
+ # Preload these once, as globals, as a micro-optimisation.
2050
+ # This makes a significant difference to the time it takes
2051
+ # to do `isinstance()`/`issubclass()` checks
2052
+ # against runtime-checkable protocols with only one callable member.
2053
+ _abc_instancecheck = ABCMeta.__instancecheck__
2054
+ _abc_subclasscheck = ABCMeta.__subclasscheck__
2055
+
2056
+
2057
+ def _type_check_issubclass_arg_1(arg):
2058
+ """Raise TypeError if `arg` is not an instance of `type`
2059
+ in `issubclass(arg, <protocol>)`.
2060
+
2061
+ In most cases, this is verified by type.__subclasscheck__.
2062
+ Checking it again unnecessarily would slow down issubclass() checks,
2063
+ so, we don't perform this check unless we absolutely have to.
2064
+
2065
+ For various error paths, however,
2066
+ we want to ensure that *this* error message is shown to the user
2067
+ where relevant, rather than a typing.py-specific error message.
2068
+ """
2069
+ if not isinstance(arg, type):
2070
+ # Same error message as for issubclass(1, int).
2071
+ raise TypeError('issubclass() arg 1 must be a class')
2072
+
2073
+
2074
+ class _ProtocolMeta(ABCMeta):
2075
+ # This metaclass is somewhat unfortunate,
2076
+ # but is necessary for several reasons...
2077
+ def __new__(mcls, name, bases, namespace, /, **kwargs):
2078
+ if name == "Protocol" and bases == (Generic,):
2079
+ pass
2080
+ elif Protocol in bases:
2081
+ for base in bases:
2082
+ if not (
2083
+ base in {object, Generic}
2084
+ or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, [])
2085
+ or (
2086
+ issubclass(base, Generic)
2087
+ and getattr(base, "_is_protocol", False)
2088
+ )
2089
+ ):
2090
+ raise TypeError(
2091
+ f"Protocols can only inherit from other protocols, "
2092
+ f"got {base!r}"
2093
+ )
2094
+ return super().__new__(mcls, name, bases, namespace, **kwargs)
2095
+
2096
+ def __init__(cls, *args, **kwargs):
2097
+ super().__init__(*args, **kwargs)
2098
+ if getattr(cls, "_is_protocol", False):
2099
+ cls.__protocol_attrs__ = _get_protocol_attrs(cls)
2100
+
2101
+ def __subclasscheck__(cls, other):
2102
+ if cls is Protocol:
2103
+ return type.__subclasscheck__(cls, other)
2104
+ if (
2105
+ getattr(cls, '_is_protocol', False)
2106
+ and not _allow_reckless_class_checks()
2107
+ ):
2108
+ if not getattr(cls, '_is_runtime_protocol', False):
2109
+ _type_check_issubclass_arg_1(other)
2110
+ raise TypeError(
2111
+ "Instance and class checks can only be used with "
2112
+ "@runtime_checkable protocols"
2113
+ )
2114
+ if (
2115
+ # this attribute is set by @runtime_checkable:
2116
+ cls.__non_callable_proto_members__
2117
+ and cls.__dict__.get("__subclasshook__") is _proto_hook
2118
+ ):
2119
+ _type_check_issubclass_arg_1(other)
2120
+ non_method_attrs = sorted(cls.__non_callable_proto_members__)
2121
+ raise TypeError(
2122
+ "Protocols with non-method members don't support issubclass()."
2123
+ f" Non-method members: {str(non_method_attrs)[1:-1]}."
2124
+ )
2125
+ return _abc_subclasscheck(cls, other)
2126
+
2127
+ def __instancecheck__(cls, instance):
2128
+ # We need this method for situations where attributes are
2129
+ # assigned in __init__.
2130
+ if cls is Protocol:
2131
+ return type.__instancecheck__(cls, instance)
2132
+ if not getattr(cls, "_is_protocol", False):
2133
+ # i.e., it's a concrete subclass of a protocol
2134
+ return _abc_instancecheck(cls, instance)
2135
+
2136
+ if (
2137
+ not getattr(cls, '_is_runtime_protocol', False) and
2138
+ not _allow_reckless_class_checks()
2139
+ ):
2140
+ raise TypeError("Instance and class checks can only be used with"
2141
+ " @runtime_checkable protocols")
2142
+
2143
+ if _abc_instancecheck(cls, instance):
2144
+ return True
2145
+
2146
+ getattr_static = _lazy_load_getattr_static()
2147
+ for attr in cls.__protocol_attrs__:
2148
+ try:
2149
+ val = getattr_static(instance, attr)
2150
+ except AttributeError:
2151
+ break
2152
+ # this attribute is set by @runtime_checkable:
2153
+ if val is None and attr not in cls.__non_callable_proto_members__:
2154
+ break
2155
+ else:
2156
+ return True
2157
+
2158
+ return False
2159
+
2160
+
2161
+ @classmethod
2162
+ def _proto_hook(cls, other):
2163
+ if not cls.__dict__.get('_is_protocol', False):
2164
+ return NotImplemented
2165
+
2166
+ for attr in cls.__protocol_attrs__:
2167
+ for base in other.__mro__:
2168
+ # Check if the members appears in the class dictionary...
2169
+ if attr in base.__dict__:
2170
+ if base.__dict__[attr] is None:
2171
+ return NotImplemented
2172
+ break
2173
+
2174
+ # ...or in annotations, if it is a sub-protocol.
2175
+ annotations = getattr(base, '__annotations__', {})
2176
+ if (isinstance(annotations, collections.abc.Mapping) and
2177
+ attr in annotations and
2178
+ issubclass(other, Generic) and getattr(other, '_is_protocol', False)):
2179
+ break
2180
+ else:
2181
+ return NotImplemented
2182
+ return True
2183
+
2184
+
2185
+ class Protocol(Generic, metaclass=_ProtocolMeta):
2186
+ """Base class for protocol classes.
2187
+
2188
+ Protocol classes are defined as::
2189
+
2190
+ class Proto(Protocol):
2191
+ def meth(self) -> int:
2192
+ ...
2193
+
2194
+ Such classes are primarily used with static type checkers that recognize
2195
+ structural subtyping (static duck-typing).
2196
+
2197
+ For example::
2198
+
2199
+ class C:
2200
+ def meth(self) -> int:
2201
+ return 0
2202
+
2203
+ def func(x: Proto) -> int:
2204
+ return x.meth()
2205
+
2206
+ func(C()) # Passes static type check
2207
+
2208
+ See PEP 544 for details. Protocol classes decorated with
2209
+ @typing.runtime_checkable act as simple-minded runtime protocols that check
2210
+ only the presence of given attributes, ignoring their type signatures.
2211
+ Protocol classes can be generic, they are defined as::
2212
+
2213
+ class GenProto[T](Protocol):
2214
+ def meth(self) -> T:
2215
+ ...
2216
+ """
2217
+
2218
+ __slots__ = ()
2219
+ _is_protocol = True
2220
+ _is_runtime_protocol = False
2221
+
2222
+ def __init_subclass__(cls, *args, **kwargs):
2223
+ super().__init_subclass__(*args, **kwargs)
2224
+
2225
+ # Determine if this is a protocol or a concrete subclass.
2226
+ if not cls.__dict__.get('_is_protocol', False):
2227
+ cls._is_protocol = any(b is Protocol for b in cls.__bases__)
2228
+
2229
+ # Set (or override) the protocol subclass hook.
2230
+ if '__subclasshook__' not in cls.__dict__:
2231
+ cls.__subclasshook__ = _proto_hook
2232
+
2233
+ # Prohibit instantiation for protocol classes
2234
+ if cls._is_protocol and cls.__init__ is Protocol.__init__:
2235
+ cls.__init__ = _no_init_or_replace_init
2236
+
2237
+
2238
+ class _AnnotatedAlias(_NotIterable, _GenericAlias, _root=True):
2239
+ """Runtime representation of an annotated type.
2240
+
2241
+ At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
2242
+ with extra annotations. The alias behaves like a normal typing alias.
2243
+ Instantiating is the same as instantiating the underlying type; binding
2244
+ it to types is also the same.
2245
+
2246
+ The metadata itself is stored in a '__metadata__' attribute as a tuple.
2247
+ """
2248
+
2249
+ def __init__(self, origin, metadata):
2250
+ if isinstance(origin, _AnnotatedAlias):
2251
+ metadata = origin.__metadata__ + metadata
2252
+ origin = origin.__origin__
2253
+ super().__init__(origin, origin, name='Annotated')
2254
+ self.__metadata__ = metadata
2255
+
2256
+ def copy_with(self, params):
2257
+ assert len(params) == 1
2258
+ new_type = params[0]
2259
+ return _AnnotatedAlias(new_type, self.__metadata__)
2260
+
2261
+ def __repr__(self):
2262
+ return "typing.Annotated[{}, {}]".format(
2263
+ _type_repr(self.__origin__),
2264
+ ", ".join(repr(a) for a in self.__metadata__)
2265
+ )
2266
+
2267
+ def __reduce__(self):
2268
+ return operator.getitem, (
2269
+ Annotated, (self.__origin__,) + self.__metadata__
2270
+ )
2271
+
2272
+ def __eq__(self, other):
2273
+ if not isinstance(other, _AnnotatedAlias):
2274
+ return NotImplemented
2275
+ return (self.__origin__ == other.__origin__
2276
+ and self.__metadata__ == other.__metadata__)
2277
+
2278
+ def __hash__(self):
2279
+ return hash((self.__origin__, self.__metadata__))
2280
+
2281
+ def __getattr__(self, attr):
2282
+ if attr in {'__name__', '__qualname__'}:
2283
+ return 'Annotated'
2284
+ return super().__getattr__(attr)
2285
+
2286
+ def __mro_entries__(self, bases):
2287
+ return (self.__origin__,)
2288
+
2289
+
2290
+ @_TypedCacheSpecialForm
2291
+ @_tp_cache(typed=True)
2292
+ def Annotated(self, *params):
2293
+ """Add context-specific metadata to a type.
2294
+
2295
+ Example: Annotated[int, runtime_check.Unsigned] indicates to the
2296
+ hypothetical runtime_check module that this type is an unsigned int.
2297
+ Every other consumer of this type can ignore this metadata and treat
2298
+ this type as int.
2299
+
2300
+ The first argument to Annotated must be a valid type.
2301
+
2302
+ Details:
2303
+
2304
+ - It's an error to call `Annotated` with less than two arguments.
2305
+ - Access the metadata via the ``__metadata__`` attribute::
2306
+
2307
+ assert Annotated[int, '$'].__metadata__ == ('$',)
2308
+
2309
+ - Nested Annotated types are flattened::
2310
+
2311
+ assert Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
2312
+
2313
+ - Instantiating an annotated type is equivalent to instantiating the
2314
+ underlying type::
2315
+
2316
+ assert Annotated[C, Ann1](5) == C(5)
2317
+
2318
+ - Annotated can be used as a generic type alias::
2319
+
2320
+ type Optimized[T] = Annotated[T, runtime.Optimize()]
2321
+ # type checker will treat Optimized[int]
2322
+ # as equivalent to Annotated[int, runtime.Optimize()]
2323
+
2324
+ type OptimizedList[T] = Annotated[list[T], runtime.Optimize()]
2325
+ # type checker will treat OptimizedList[int]
2326
+ # as equivalent to Annotated[list[int], runtime.Optimize()]
2327
+
2328
+ - Annotated cannot be used with an unpacked TypeVarTuple::
2329
+
2330
+ type Variadic[*Ts] = Annotated[*Ts, Ann1] # NOT valid
2331
+
2332
+ This would be equivalent to::
2333
+
2334
+ Annotated[T1, T2, T3, ..., Ann1]
2335
+
2336
+ where T1, T2 etc. are TypeVars, which would be invalid, because
2337
+ only one type should be passed to Annotated.
2338
+ """
2339
+ if len(params) < 2:
2340
+ raise TypeError("Annotated[...] should be used "
2341
+ "with at least two arguments (a type and an "
2342
+ "annotation).")
2343
+ if _is_unpacked_typevartuple(params[0]):
2344
+ raise TypeError("Annotated[...] should not be used with an "
2345
+ "unpacked TypeVarTuple")
2346
+ msg = "Annotated[t, ...]: t must be a type."
2347
+ origin = _type_check(params[0], msg, allow_special_forms=True)
2348
+ metadata = tuple(params[1:])
2349
+ return _AnnotatedAlias(origin, metadata)
2350
+
2351
+
2352
+ def runtime_checkable(cls):
2353
+ """Mark a protocol class as a runtime protocol.
2354
+
2355
+ Such protocol can be used with isinstance() and issubclass().
2356
+ Raise TypeError if applied to a non-protocol class.
2357
+ This allows a simple-minded structural check very similar to
2358
+ one-trick ponies in collections.abc such as Iterable.
2359
+
2360
+ For example::
2361
+
2362
+ @runtime_checkable
2363
+ class Closable(Protocol):
2364
+ def close(self): ...
2365
+
2366
+ assert isinstance(open('/some/file'), Closable)
2367
+
2368
+ Warning: this will check only the presence of the required methods,
2369
+ not their type signatures!
2370
+ """
2371
+ if not issubclass(cls, Generic) or not getattr(cls, '_is_protocol', False):
2372
+ raise TypeError('@runtime_checkable can be only applied to protocol classes,'
2373
+ ' got %r' % cls)
2374
+ cls._is_runtime_protocol = True
2375
+ # PEP 544 prohibits using issubclass()
2376
+ # with protocols that have non-method members.
2377
+ # See gh-113320 for why we compute this attribute here,
2378
+ # rather than in `_ProtocolMeta.__init__`
2379
+ cls.__non_callable_proto_members__ = set()
2380
+ for attr in cls.__protocol_attrs__:
2381
+ try:
2382
+ is_callable = callable(getattr(cls, attr, None))
2383
+ except Exception as e:
2384
+ raise TypeError(
2385
+ f"Failed to determine whether protocol member {attr!r} "
2386
+ "is a method member"
2387
+ ) from e
2388
+ else:
2389
+ if not is_callable:
2390
+ cls.__non_callable_proto_members__.add(attr)
2391
+ return cls
2392
+
2393
+
2394
+ def cast(typ, val):
2395
+ """Cast a value to a type.
2396
+
2397
+ This returns the value unchanged. To the type checker this
2398
+ signals that the return value has the designated type, but at
2399
+ runtime we intentionally don't check anything (we want this
2400
+ to be as fast as possible).
2401
+ """
2402
+ return val
2403
+
2404
+
2405
+ def assert_type(val, typ, /):
2406
+ """Ask a static type checker to confirm that the value is of the given type.
2407
+
2408
+ At runtime this does nothing: it returns the first argument unchanged with no
2409
+ checks or side effects, no matter the actual type of the argument.
2410
+
2411
+ When a static type checker encounters a call to assert_type(), it
2412
+ emits an error if the value is not of the specified type::
2413
+
2414
+ def greet(name: str) -> None:
2415
+ assert_type(name, str) # OK
2416
+ assert_type(name, int) # type checker error
2417
+ """
2418
+ return val
2419
+
2420
+
2421
+ _allowed_types = (types.FunctionType, types.BuiltinFunctionType,
2422
+ types.MethodType, types.ModuleType,
2423
+ WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
2424
+
2425
+
2426
+ def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
2427
+ """Return type hints for an object.
2428
+
2429
+ This is often the same as inspect.get_annotations(obj) or obj.__annotations__,
2430
+ but it handles forward references encoded as string literals and recursively replaces all
2431
+ 'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
2432
+
2433
+ The argument may be a module, class, method, or function. The annotations
2434
+ are returned as a dictionary. For classes, annotations include also
2435
+ inherited members.
2436
+
2437
+ TypeError is raised if the argument is not of a type that can contain
2438
+ annotations, and an empty dictionary is returned if no annotations are
2439
+ present.
2440
+
2441
+ BEWARE -- the behavior of globalns and localns is counterintuitive
2442
+ (unless you are familiar with how eval() and exec() work). The
2443
+ search order is locals first, then globals.
2444
+
2445
+ - If no dict arguments are passed, an attempt is made to use the
2446
+ globals from obj (or the respective module's globals for classes),
2447
+ and these are also used as the locals. If the object does not appear
2448
+ to have globals, an empty dictionary is used. For classes, the search
2449
+ order is globals first then locals.
2450
+
2451
+ - If one dict argument is passed, it is used for both globals and
2452
+ locals.
2453
+
2454
+ - If two dict arguments are passed, they specify globals and
2455
+ locals, respectively.
2456
+ """
2457
+ if getattr(obj, '__no_type_check__', None):
2458
+ return {}
2459
+ # Classes require a special treatment.
2460
+ if isinstance(obj, type):
2461
+ hints = {}
2462
+ for base in reversed(obj.__mro__):
2463
+ if globalns is None:
2464
+ base_globals = getattr(sys.modules.get(base.__module__, None), '__dict__', {})
2465
+ else:
2466
+ base_globals = globalns
2467
+ ann = base.__dict__.get('__annotations__', {})
2468
+ if isinstance(ann, types.GetSetDescriptorType):
2469
+ ann = {}
2470
+ base_locals = dict(vars(base)) if localns is None else localns
2471
+ if localns is None and globalns is None:
2472
+ # This is surprising, but required. Before Python 3.10,
2473
+ # get_type_hints only evaluated the globalns of
2474
+ # a class. To maintain backwards compatibility, we reverse
2475
+ # the globalns and localns order so that eval() looks into
2476
+ # *base_globals* first rather than *base_locals*.
2477
+ # This only affects ForwardRefs.
2478
+ base_globals, base_locals = base_locals, base_globals
2479
+ for name, value in ann.items():
2480
+ if value is None:
2481
+ value = type(None)
2482
+ if isinstance(value, str):
2483
+ value = ForwardRef(value, is_argument=False, is_class=True)
2484
+ value = _eval_type(value, base_globals, base_locals, base.__type_params__)
2485
+ hints[name] = value
2486
+ return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
2487
+
2488
+ if globalns is None:
2489
+ if isinstance(obj, types.ModuleType):
2490
+ globalns = obj.__dict__
2491
+ else:
2492
+ nsobj = obj
2493
+ # Find globalns for the unwrapped object.
2494
+ seen = {id(nsobj)}
2495
+ while hasattr(nsobj, '__wrapped__'):
2496
+ nsobj = nsobj.__wrapped__
2497
+ if id(nsobj) in seen:
2498
+ raise ValueError(f'wrapper loop when unwrapping {obj!r}')
2499
+ seen.add(id(nsobj))
2500
+ globalns = getattr(nsobj, '__globals__', {})
2501
+ if localns is None:
2502
+ localns = globalns
2503
+ elif localns is None:
2504
+ localns = globalns
2505
+ hints = getattr(obj, '__annotations__', None)
2506
+ if hints is None:
2507
+ # Return empty annotations for something that _could_ have them.
2508
+ if isinstance(obj, _allowed_types):
2509
+ return {}
2510
+ else:
2511
+ raise TypeError('{!r} is not a module, class, method, '
2512
+ 'or function.'.format(obj))
2513
+ hints = dict(hints)
2514
+ type_params = getattr(obj, "__type_params__", ())
2515
+ for name, value in hints.items():
2516
+ if value is None:
2517
+ value = type(None)
2518
+ if isinstance(value, str):
2519
+ # class-level forward refs were handled above, this must be either
2520
+ # a module-level annotation or a function argument annotation
2521
+ value = ForwardRef(
2522
+ value,
2523
+ is_argument=not isinstance(obj, types.ModuleType),
2524
+ is_class=False,
2525
+ )
2526
+ hints[name] = _eval_type(value, globalns, localns, type_params)
2527
+ return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
2528
+
2529
+
2530
+ def _strip_annotations(t):
2531
+ """Strip the annotations from a given type."""
2532
+ if isinstance(t, _AnnotatedAlias):
2533
+ return _strip_annotations(t.__origin__)
2534
+ if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnly):
2535
+ return _strip_annotations(t.__args__[0])
2536
+ if isinstance(t, _GenericAlias):
2537
+ stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
2538
+ if stripped_args == t.__args__:
2539
+ return t
2540
+ return t.copy_with(stripped_args)
2541
+ if isinstance(t, GenericAlias):
2542
+ stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
2543
+ if stripped_args == t.__args__:
2544
+ return t
2545
+ return GenericAlias(t.__origin__, stripped_args)
2546
+ if isinstance(t, types.UnionType):
2547
+ stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
2548
+ if stripped_args == t.__args__:
2549
+ return t
2550
+ return functools.reduce(operator.or_, stripped_args)
2551
+
2552
+ return t
2553
+
2554
+
2555
+ def get_origin(tp):
2556
+ """Get the unsubscripted version of a type.
2557
+
2558
+ This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar,
2559
+ Annotated, and others. Return None for unsupported types.
2560
+
2561
+ Examples::
2562
+
2563
+ >>> P = ParamSpec('P')
2564
+ >>> assert get_origin(Literal[42]) is Literal
2565
+ >>> assert get_origin(int) is None
2566
+ >>> assert get_origin(ClassVar[int]) is ClassVar
2567
+ >>> assert get_origin(Generic) is Generic
2568
+ >>> assert get_origin(Generic[T]) is Generic
2569
+ >>> assert get_origin(Union[T, int]) is Union
2570
+ >>> assert get_origin(List[Tuple[T, T]][int]) is list
2571
+ >>> assert get_origin(P.args) is P
2572
+ """
2573
+ if isinstance(tp, _AnnotatedAlias):
2574
+ return Annotated
2575
+ if isinstance(tp, (_BaseGenericAlias, GenericAlias,
2576
+ ParamSpecArgs, ParamSpecKwargs)):
2577
+ return tp.__origin__
2578
+ if tp is Generic:
2579
+ return Generic
2580
+ if isinstance(tp, types.UnionType):
2581
+ return types.UnionType
2582
+ return None
2583
+
2584
+
2585
+ def get_args(tp):
2586
+ """Get type arguments with all substitutions performed.
2587
+
2588
+ For unions, basic simplifications used by Union constructor are performed.
2589
+
2590
+ Examples::
2591
+
2592
+ >>> T = TypeVar('T')
2593
+ >>> assert get_args(Dict[str, int]) == (str, int)
2594
+ >>> assert get_args(int) == ()
2595
+ >>> assert get_args(Union[int, Union[T, int], str][int]) == (int, str)
2596
+ >>> assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
2597
+ >>> assert get_args(Callable[[], T][int]) == ([], int)
2598
+ """
2599
+ if isinstance(tp, _AnnotatedAlias):
2600
+ return (tp.__origin__,) + tp.__metadata__
2601
+ if isinstance(tp, (_GenericAlias, GenericAlias)):
2602
+ res = tp.__args__
2603
+ if _should_unflatten_callable_args(tp, res):
2604
+ res = (list(res[:-1]), res[-1])
2605
+ return res
2606
+ if isinstance(tp, types.UnionType):
2607
+ return tp.__args__
2608
+ return ()
2609
+
2610
+
2611
+ def is_typeddict(tp):
2612
+ """Check if an object is a TypedDict class.
2613
+
2614
+ For example::
2615
+
2616
+ >>> from typing import TypedDict
2617
+ >>> class Film(TypedDict):
2618
+ ... title: str
2619
+ ... year: int
2620
+ ...
2621
+ >>> is_typeddict(Film)
2622
+ True
2623
+ >>> is_typeddict(dict)
2624
+ False
2625
+ """
2626
+ return isinstance(tp, _TypedDictMeta)
2627
+
2628
+
2629
+ _ASSERT_NEVER_REPR_MAX_LENGTH = 100
2630
+
2631
+
2632
+ def assert_never(arg: Never, /) -> Never:
2633
+ """Statically assert that a line of code is unreachable.
2634
+
2635
+ Example::
2636
+
2637
+ def int_or_str(arg: int | str) -> None:
2638
+ match arg:
2639
+ case int():
2640
+ print("It's an int")
2641
+ case str():
2642
+ print("It's a str")
2643
+ case _:
2644
+ assert_never(arg)
2645
+
2646
+ If a type checker finds that a call to assert_never() is
2647
+ reachable, it will emit an error.
2648
+
2649
+ At runtime, this throws an exception when called.
2650
+ """
2651
+ value = repr(arg)
2652
+ if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH:
2653
+ value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...'
2654
+ raise AssertionError(f"Expected code to be unreachable, but got: {value}")
2655
+
2656
+
2657
+ def no_type_check(arg):
2658
+ """Decorator to indicate that annotations are not type hints.
2659
+
2660
+ The argument must be a class or function; if it is a class, it
2661
+ applies recursively to all methods and classes defined in that class
2662
+ (but not to methods defined in its superclasses or subclasses).
2663
+
2664
+ This mutates the function(s) or class(es) in place.
2665
+ """
2666
+ if isinstance(arg, type):
2667
+ for key in dir(arg):
2668
+ obj = getattr(arg, key)
2669
+ if (
2670
+ not hasattr(obj, '__qualname__')
2671
+ or obj.__qualname__ != f'{arg.__qualname__}.{obj.__name__}'
2672
+ or getattr(obj, '__module__', None) != arg.__module__
2673
+ ):
2674
+ # We only modify objects that are defined in this type directly.
2675
+ # If classes / methods are nested in multiple layers,
2676
+ # we will modify them when processing their direct holders.
2677
+ continue
2678
+ # Instance, class, and static methods:
2679
+ if isinstance(obj, types.FunctionType):
2680
+ obj.__no_type_check__ = True
2681
+ if isinstance(obj, types.MethodType):
2682
+ obj.__func__.__no_type_check__ = True
2683
+ # Nested types:
2684
+ if isinstance(obj, type):
2685
+ no_type_check(obj)
2686
+ try:
2687
+ arg.__no_type_check__ = True
2688
+ except TypeError: # built-in classes
2689
+ pass
2690
+ return arg
2691
+
2692
+
2693
+ def no_type_check_decorator(decorator):
2694
+ """Decorator to give another decorator the @no_type_check effect.
2695
+
2696
+ This wraps the decorator with something that wraps the decorated
2697
+ function in @no_type_check.
2698
+ """
2699
+ import warnings
2700
+ warnings._deprecated("typing.no_type_check_decorator", remove=(3, 15))
2701
+ @functools.wraps(decorator)
2702
+ def wrapped_decorator(*args, **kwds):
2703
+ func = decorator(*args, **kwds)
2704
+ func = no_type_check(func)
2705
+ return func
2706
+
2707
+ return wrapped_decorator
2708
+
2709
+
2710
+ def _overload_dummy(*args, **kwds):
2711
+ """Helper for @overload to raise when called."""
2712
+ raise NotImplementedError(
2713
+ "You should not call an overloaded function. "
2714
+ "A series of @overload-decorated functions "
2715
+ "outside a stub module should always be followed "
2716
+ "by an implementation that is not @overload-ed.")
2717
+
2718
+
2719
+ # {module: {qualname: {firstlineno: func}}}
2720
+ _overload_registry = defaultdict(functools.partial(defaultdict, dict))
2721
+
2722
+
2723
+ def overload(func):
2724
+ """Decorator for overloaded functions/methods.
2725
+
2726
+ In a non-stub file, place two or more stub definitions for the same
2727
+ function in a row, each decorated with @overload, followed
2728
+ by an implementation. The implementation should *not*
2729
+ be decorated with @overload::
2730
+
2731
+ @overload
2732
+ def utf8(value: None) -> None: ...
2733
+ @overload
2734
+ def utf8(value: bytes) -> bytes: ...
2735
+ @overload
2736
+ def utf8(value: str) -> bytes: ...
2737
+ def utf8(value):
2738
+ ... # implementation goes here
2739
+
2740
+ In a stub file or in an abstract method (for example, in a Protocol definition),
2741
+ the implementation may be omitted::
2742
+
2743
+ @overload
2744
+ def utf8(value: None) -> None: ...
2745
+ @overload
2746
+ def utf8(value: bytes) -> bytes: ...
2747
+ @overload
2748
+ def utf8(value: str) -> bytes: ...
2749
+
2750
+ The overloads for a function can be retrieved at runtime using the
2751
+ get_overloads() function.
2752
+ """
2753
+ # classmethod and staticmethod
2754
+ f = getattr(func, "__func__", func)
2755
+ try:
2756
+ _overload_registry[f.__module__][f.__qualname__][f.__code__.co_firstlineno] = func
2757
+ except AttributeError:
2758
+ # Not a normal function; ignore.
2759
+ pass
2760
+ return _overload_dummy
2761
+
2762
+
2763
+ def get_overloads(func):
2764
+ """Return all defined overloads for *func* as a sequence."""
2765
+ # classmethod and staticmethod
2766
+ f = getattr(func, "__func__", func)
2767
+ if f.__module__ not in _overload_registry:
2768
+ return []
2769
+ mod_dict = _overload_registry[f.__module__]
2770
+ if f.__qualname__ not in mod_dict:
2771
+ return []
2772
+ return list(mod_dict[f.__qualname__].values())
2773
+
2774
+
2775
+ def clear_overloads():
2776
+ """Clear all overloads in the registry."""
2777
+ _overload_registry.clear()
2778
+
2779
+
2780
+ def final(f):
2781
+ """Decorator to indicate final methods and final classes.
2782
+
2783
+ Use this decorator to indicate to type checkers that the decorated
2784
+ method cannot be overridden, and the decorated class cannot be subclassed.
2785
+
2786
+ For example::
2787
+
2788
+ class Base:
2789
+ @final
2790
+ def done(self) -> None:
2791
+ ...
2792
+ class Sub(Base):
2793
+ def done(self) -> None: # Error reported by type checker
2794
+ ...
2795
+
2796
+ @final
2797
+ class Leaf:
2798
+ ...
2799
+ class Other(Leaf): # Error reported by type checker
2800
+ ...
2801
+
2802
+ There is no runtime checking of these properties. The decorator
2803
+ attempts to set the ``__final__`` attribute to ``True`` on the decorated
2804
+ object to allow runtime introspection.
2805
+ """
2806
+ try:
2807
+ f.__final__ = True
2808
+ except (AttributeError, TypeError):
2809
+ # Skip the attribute silently if it is not writable.
2810
+ # AttributeError happens if the object has __slots__ or a
2811
+ # read-only property, TypeError if it's a builtin class.
2812
+ pass
2813
+ return f
2814
+
2815
+
2816
+ # Some unconstrained type variables. These were initially used by the container types.
2817
+ # They were never meant for export and are now unused, but we keep them around to
2818
+ # avoid breaking compatibility with users who import them.
2819
+ T = TypeVar('T') # Any type.
2820
+ KT = TypeVar('KT') # Key type.
2821
+ VT = TypeVar('VT') # Value type.
2822
+ T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
2823
+ V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
2824
+ VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
2825
+ T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
2826
+ # Internal type bound to class object types.
2827
+ CT_co = TypeVar('CT_co', covariant=True, bound=type)
2828
+
2829
+
2830
+ # A useful type variable with constraints. This represents string types.
2831
+ # (This one *is* for export!)
2832
+ AnyStr = TypeVar('AnyStr', bytes, str)
2833
+
2834
+
2835
+ # Various ABCs mimicking those in collections.abc.
2836
+ _alias = _SpecialGenericAlias
2837
+
2838
+ Hashable = _alias(collections.abc.Hashable, 0) # Not generic.
2839
+ Awaitable = _alias(collections.abc.Awaitable, 1)
2840
+ Coroutine = _alias(collections.abc.Coroutine, 3)
2841
+ AsyncIterable = _alias(collections.abc.AsyncIterable, 1)
2842
+ AsyncIterator = _alias(collections.abc.AsyncIterator, 1)
2843
+ Iterable = _alias(collections.abc.Iterable, 1)
2844
+ Iterator = _alias(collections.abc.Iterator, 1)
2845
+ Reversible = _alias(collections.abc.Reversible, 1)
2846
+ Sized = _alias(collections.abc.Sized, 0) # Not generic.
2847
+ Container = _alias(collections.abc.Container, 1)
2848
+ Collection = _alias(collections.abc.Collection, 1)
2849
+ Callable = _CallableType(collections.abc.Callable, 2)
2850
+ Callable.__doc__ = \
2851
+ """Deprecated alias to collections.abc.Callable.
2852
+
2853
+ Callable[[int], str] signifies a function that takes a single
2854
+ parameter of type int and returns a str.
2855
+
2856
+ The subscription syntax must always be used with exactly two
2857
+ values: the argument list and the return type.
2858
+ The argument list must be a list of types, a ParamSpec,
2859
+ Concatenate or ellipsis. The return type must be a single type.
2860
+
2861
+ There is no syntax to indicate optional or keyword arguments;
2862
+ such function types are rarely used as callback types.
2863
+ """
2864
+ AbstractSet = _alias(collections.abc.Set, 1, name='AbstractSet')
2865
+ MutableSet = _alias(collections.abc.MutableSet, 1)
2866
+ # NOTE: Mapping is only covariant in the value type.
2867
+ Mapping = _alias(collections.abc.Mapping, 2)
2868
+ MutableMapping = _alias(collections.abc.MutableMapping, 2)
2869
+ Sequence = _alias(collections.abc.Sequence, 1)
2870
+ MutableSequence = _alias(collections.abc.MutableSequence, 1)
2871
+ ByteString = _DeprecatedGenericAlias(
2872
+ collections.abc.ByteString, 0, removal_version=(3, 17) # Not generic.
2873
+ )
2874
+ # Tuple accepts variable number of parameters.
2875
+ Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
2876
+ Tuple.__doc__ = \
2877
+ """Deprecated alias to builtins.tuple.
2878
+
2879
+ Tuple[X, Y] is the cross-product type of X and Y.
2880
+
2881
+ Example: Tuple[T1, T2] is a tuple of two elements corresponding
2882
+ to type variables T1 and T2. Tuple[int, float, str] is a tuple
2883
+ of an int, a float and a string.
2884
+
2885
+ To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
2886
+ """
2887
+ List = _alias(list, 1, inst=False, name='List')
2888
+ Deque = _alias(collections.deque, 1, name='Deque')
2889
+ Set = _alias(set, 1, inst=False, name='Set')
2890
+ FrozenSet = _alias(frozenset, 1, inst=False, name='FrozenSet')
2891
+ MappingView = _alias(collections.abc.MappingView, 1)
2892
+ KeysView = _alias(collections.abc.KeysView, 1)
2893
+ ItemsView = _alias(collections.abc.ItemsView, 2)
2894
+ ValuesView = _alias(collections.abc.ValuesView, 1)
2895
+ Dict = _alias(dict, 2, inst=False, name='Dict')
2896
+ DefaultDict = _alias(collections.defaultdict, 2, name='DefaultDict')
2897
+ OrderedDict = _alias(collections.OrderedDict, 2)
2898
+ Counter = _alias(collections.Counter, 1)
2899
+ ChainMap = _alias(collections.ChainMap, 2)
2900
+ Generator = _alias(collections.abc.Generator, 3, defaults=(types.NoneType, types.NoneType))
2901
+ AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2, defaults=(types.NoneType,))
2902
+ Type = _alias(type, 1, inst=False, name='Type')
2903
+ Type.__doc__ = \
2904
+ """Deprecated alias to builtins.type.
2905
+
2906
+ builtins.type or typing.Type can be used to annotate class objects.
2907
+ For example, suppose we have the following classes::
2908
+
2909
+ class User: ... # Abstract base for User classes
2910
+ class BasicUser(User): ...
2911
+ class ProUser(User): ...
2912
+ class TeamUser(User): ...
2913
+
2914
+ And a function that takes a class argument that's a subclass of
2915
+ User and returns an instance of the corresponding class::
2916
+
2917
+ def new_user[U](user_class: type[U]) -> U:
2918
+ user = user_class()
2919
+ # (Here we could write the user object to a database)
2920
+ return user
2921
+
2922
+ joe = new_user(BasicUser)
2923
+
2924
+ At this point the type checker knows that joe has type BasicUser.
2925
+ """
2926
+
2927
+
2928
+ @runtime_checkable
2929
+ class SupportsInt(Protocol):
2930
+ """A protocol with one abstract method __int__."""
2931
+
2932
+ __slots__ = ()
2933
+
2934
+ @abstractmethod
2935
+ def __int__(self) -> int:
2936
+ pass
2937
+
2938
+
2939
+ @runtime_checkable
2940
+ class SupportsFloat(Protocol):
2941
+ """A protocol with one abstract method __float__."""
2942
+
2943
+ __slots__ = ()
2944
+
2945
+ @abstractmethod
2946
+ def __float__(self) -> float:
2947
+ pass
2948
+
2949
+
2950
+ @runtime_checkable
2951
+ class SupportsComplex(Protocol):
2952
+ """A protocol with one abstract method __complex__."""
2953
+
2954
+ __slots__ = ()
2955
+
2956
+ @abstractmethod
2957
+ def __complex__(self) -> complex:
2958
+ pass
2959
+
2960
+
2961
+ @runtime_checkable
2962
+ class SupportsBytes(Protocol):
2963
+ """A protocol with one abstract method __bytes__."""
2964
+
2965
+ __slots__ = ()
2966
+
2967
+ @abstractmethod
2968
+ def __bytes__(self) -> bytes:
2969
+ pass
2970
+
2971
+
2972
+ @runtime_checkable
2973
+ class SupportsIndex(Protocol):
2974
+ """A protocol with one abstract method __index__."""
2975
+
2976
+ __slots__ = ()
2977
+
2978
+ @abstractmethod
2979
+ def __index__(self) -> int:
2980
+ pass
2981
+
2982
+
2983
+ @runtime_checkable
2984
+ class SupportsAbs[T](Protocol):
2985
+ """A protocol with one abstract method __abs__ that is covariant in its return type."""
2986
+
2987
+ __slots__ = ()
2988
+
2989
+ @abstractmethod
2990
+ def __abs__(self) -> T:
2991
+ pass
2992
+
2993
+
2994
+ @runtime_checkable
2995
+ class SupportsRound[T](Protocol):
2996
+ """A protocol with one abstract method __round__ that is covariant in its return type."""
2997
+
2998
+ __slots__ = ()
2999
+
3000
+ @abstractmethod
3001
+ def __round__(self, ndigits: int = 0) -> T:
3002
+ pass
3003
+
3004
+
3005
+ def _make_nmtuple(name, types, module, defaults = ()):
3006
+ fields = [n for n, t in types]
3007
+ types = {n: _type_check(t, f"field {n} annotation must be a type")
3008
+ for n, t in types}
3009
+ nm_tpl = collections.namedtuple(name, fields,
3010
+ defaults=defaults, module=module)
3011
+ nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = types
3012
+ return nm_tpl
3013
+
3014
+
3015
+ # attributes prohibited to set in NamedTuple class syntax
3016
+ _prohibited = frozenset({'__new__', '__init__', '__slots__', '__getnewargs__',
3017
+ '_fields', '_field_defaults',
3018
+ '_make', '_replace', '_asdict', '_source'})
3019
+
3020
+ _special = frozenset({'__module__', '__name__', '__annotations__'})
3021
+
3022
+
3023
+ class NamedTupleMeta(type):
3024
+ def __new__(cls, typename, bases, ns):
3025
+ assert _NamedTuple in bases
3026
+ for base in bases:
3027
+ if base is not _NamedTuple and base is not Generic:
3028
+ raise TypeError(
3029
+ 'can only inherit from a NamedTuple type and Generic')
3030
+ bases = tuple(tuple if base is _NamedTuple else base for base in bases)
3031
+ types = ns.get('__annotations__', {})
3032
+ default_names = []
3033
+ for field_name in types:
3034
+ if field_name in ns:
3035
+ default_names.append(field_name)
3036
+ elif default_names:
3037
+ raise TypeError(f"Non-default namedtuple field {field_name} "
3038
+ f"cannot follow default field"
3039
+ f"{'s' if len(default_names) > 1 else ''} "
3040
+ f"{', '.join(default_names)}")
3041
+ nm_tpl = _make_nmtuple(typename, types.items(),
3042
+ defaults=[ns[n] for n in default_names],
3043
+ module=ns['__module__'])
3044
+ nm_tpl.__bases__ = bases
3045
+ if Generic in bases:
3046
+ class_getitem = _generic_class_getitem
3047
+ nm_tpl.__class_getitem__ = classmethod(class_getitem)
3048
+ # update from user namespace without overriding special namedtuple attributes
3049
+ for key, val in ns.items():
3050
+ if key in _prohibited:
3051
+ raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
3052
+ elif key not in _special:
3053
+ if key not in nm_tpl._fields:
3054
+ setattr(nm_tpl, key, val)
3055
+ try:
3056
+ set_name = type(val).__set_name__
3057
+ except AttributeError:
3058
+ pass
3059
+ else:
3060
+ try:
3061
+ set_name(val, nm_tpl, key)
3062
+ except BaseException as e:
3063
+ e.add_note(
3064
+ f"Error calling __set_name__ on {type(val).__name__!r} "
3065
+ f"instance {key!r} in {typename!r}"
3066
+ )
3067
+ raise
3068
+
3069
+ if Generic in bases:
3070
+ nm_tpl.__init_subclass__()
3071
+ return nm_tpl
3072
+
3073
+
3074
+ def NamedTuple(typename, fields=_sentinel, /, **kwargs):
3075
+ """Typed version of collections.namedtuple.
3076
+
3077
+ Usage::
3078
+
3079
+ class Employee(NamedTuple):
3080
+ name: str
3081
+ id: int
3082
+
3083
+ This is equivalent to::
3084
+
3085
+ Employee = collections.namedtuple('Employee', ['name', 'id'])
3086
+
3087
+ The types for each field name can be retrieved by calling
3088
+ inspect.get_annotations(Employee). (The field names are also in
3089
+ the _fields attribute, which is part of the namedtuple API.)
3090
+ An alternative equivalent functional syntax is also accepted::
3091
+
3092
+ Employee = NamedTuple('Employee', [('name', str), ('id', int)])
3093
+ """
3094
+ if fields is _sentinel:
3095
+ if kwargs:
3096
+ deprecated_thing = "Creating NamedTuple classes using keyword arguments"
3097
+ deprecation_msg = (
3098
+ "{name} is deprecated and will be disallowed in Python {remove}. "
3099
+ "Use the class-based or functional syntax instead."
3100
+ )
3101
+ else:
3102
+ deprecated_thing = "Failing to pass a value for the 'fields' parameter"
3103
+ example = f"`{typename} = NamedTuple({typename!r}, [])`"
3104
+ deprecation_msg = (
3105
+ "{name} is deprecated and will be disallowed in Python {remove}. "
3106
+ "To create a NamedTuple class with 0 fields "
3107
+ "using the functional syntax, "
3108
+ "pass an empty list, e.g. "
3109
+ ) + example + "."
3110
+ elif fields is None:
3111
+ if kwargs:
3112
+ raise TypeError(
3113
+ "Cannot pass `None` as the 'fields' parameter "
3114
+ "and also specify fields using keyword arguments"
3115
+ )
3116
+ else:
3117
+ deprecated_thing = "Passing `None` as the 'fields' parameter"
3118
+ example = f"`{typename} = NamedTuple({typename!r}, [])`"
3119
+ deprecation_msg = (
3120
+ "{name} is deprecated and will be disallowed in Python {remove}. "
3121
+ "To create a NamedTuple class with 0 fields "
3122
+ "using the functional syntax, "
3123
+ "pass an empty list, e.g. "
3124
+ ) + example + "."
3125
+ elif kwargs:
3126
+ raise TypeError("Either list of fields or keywords"
3127
+ " can be provided to NamedTuple, not both")
3128
+ if fields is _sentinel or fields is None:
3129
+ import warnings
3130
+ warnings._deprecated(deprecated_thing, message=deprecation_msg, remove=(3, 15))
3131
+ fields = kwargs.items()
3132
+ nt = _make_nmtuple(typename, fields, module=_caller())
3133
+ nt.__orig_bases__ = (NamedTuple,)
3134
+ return nt
3135
+
3136
+ _NamedTuple = type.__new__(NamedTupleMeta, 'NamedTuple', (), {})
3137
+
3138
+ def _namedtuple_mro_entries(bases):
3139
+ assert NamedTuple in bases
3140
+ return (_NamedTuple,)
3141
+
3142
+ NamedTuple.__mro_entries__ = _namedtuple_mro_entries
3143
+
3144
+
3145
+ def _get_typeddict_qualifiers(annotation_type):
3146
+ while True:
3147
+ annotation_origin = get_origin(annotation_type)
3148
+ if annotation_origin is Annotated:
3149
+ annotation_args = get_args(annotation_type)
3150
+ if annotation_args:
3151
+ annotation_type = annotation_args[0]
3152
+ else:
3153
+ break
3154
+ elif annotation_origin is Required:
3155
+ yield Required
3156
+ (annotation_type,) = get_args(annotation_type)
3157
+ elif annotation_origin is NotRequired:
3158
+ yield NotRequired
3159
+ (annotation_type,) = get_args(annotation_type)
3160
+ elif annotation_origin is ReadOnly:
3161
+ yield ReadOnly
3162
+ (annotation_type,) = get_args(annotation_type)
3163
+ else:
3164
+ break
3165
+
3166
+
3167
+ class _TypedDictMeta(type):
3168
+ def __new__(cls, name, bases, ns, total=True):
3169
+ """Create a new typed dict class object.
3170
+
3171
+ This method is called when TypedDict is subclassed,
3172
+ or when TypedDict is instantiated. This way
3173
+ TypedDict classes can be created through both class-based and functional syntax.
3174
+ Subclasses and instances of TypedDict return actual dictionaries.
3175
+ """
3176
+ for base in bases:
3177
+ if type(base) is not _TypedDictMeta and base is not Generic:
3178
+ raise TypeError('cannot inherit from both a TypedDict type '
3179
+ 'and a non-TypedDict base class')
3180
+
3181
+ if any(issubclass(b, Generic) for b in bases):
3182
+ generic_base = (Generic,)
3183
+ else:
3184
+ generic_base = ()
3185
+
3186
+ tp_dict = type.__new__(_TypedDictMeta, name, (*generic_base, dict), ns)
3187
+
3188
+ if not hasattr(tp_dict, '__orig_bases__'):
3189
+ tp_dict.__orig_bases__ = bases
3190
+
3191
+ annotations = {}
3192
+ own_annotations = ns.get('__annotations__', {})
3193
+ msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
3194
+ own_annotations = {
3195
+ n: _type_check(tp, msg, module=tp_dict.__module__)
3196
+ for n, tp in own_annotations.items()
3197
+ }
3198
+ required_keys = set()
3199
+ optional_keys = set()
3200
+ readonly_keys = set()
3201
+ mutable_keys = set()
3202
+
3203
+ for base in bases:
3204
+ annotations.update(base.__dict__.get('__annotations__', {}))
3205
+
3206
+ base_required = base.__dict__.get('__required_keys__', set())
3207
+ required_keys |= base_required
3208
+ optional_keys -= base_required
3209
+
3210
+ base_optional = base.__dict__.get('__optional_keys__', set())
3211
+ required_keys -= base_optional
3212
+ optional_keys |= base_optional
3213
+
3214
+ readonly_keys.update(base.__dict__.get('__readonly_keys__', ()))
3215
+ mutable_keys.update(base.__dict__.get('__mutable_keys__', ()))
3216
+
3217
+ annotations.update(own_annotations)
3218
+ for annotation_key, annotation_type in own_annotations.items():
3219
+ qualifiers = set(_get_typeddict_qualifiers(annotation_type))
3220
+ if Required in qualifiers:
3221
+ is_required = True
3222
+ elif NotRequired in qualifiers:
3223
+ is_required = False
3224
+ else:
3225
+ is_required = total
3226
+
3227
+ if is_required:
3228
+ required_keys.add(annotation_key)
3229
+ optional_keys.discard(annotation_key)
3230
+ else:
3231
+ optional_keys.add(annotation_key)
3232
+ required_keys.discard(annotation_key)
3233
+
3234
+ if ReadOnly in qualifiers:
3235
+ if annotation_key in mutable_keys:
3236
+ raise TypeError(
3237
+ f"Cannot override mutable key {annotation_key!r}"
3238
+ " with read-only key"
3239
+ )
3240
+ readonly_keys.add(annotation_key)
3241
+ else:
3242
+ mutable_keys.add(annotation_key)
3243
+ readonly_keys.discard(annotation_key)
3244
+
3245
+ assert required_keys.isdisjoint(optional_keys), (
3246
+ f"Required keys overlap with optional keys in {name}:"
3247
+ f" {required_keys=}, {optional_keys=}"
3248
+ )
3249
+ tp_dict.__annotations__ = annotations
3250
+ tp_dict.__required_keys__ = frozenset(required_keys)
3251
+ tp_dict.__optional_keys__ = frozenset(optional_keys)
3252
+ tp_dict.__readonly_keys__ = frozenset(readonly_keys)
3253
+ tp_dict.__mutable_keys__ = frozenset(mutable_keys)
3254
+ tp_dict.__total__ = total
3255
+ return tp_dict
3256
+
3257
+ __call__ = dict # static method
3258
+
3259
+ def __subclasscheck__(cls, other):
3260
+ # Typed dicts are only for static structural subtyping.
3261
+ raise TypeError('TypedDict does not support instance and class checks')
3262
+
3263
+ __instancecheck__ = __subclasscheck__
3264
+
3265
+
3266
+ def TypedDict(typename, fields=_sentinel, /, *, total=True):
3267
+ """A simple typed namespace. At runtime it is equivalent to a plain dict.
3268
+
3269
+ TypedDict creates a dictionary type such that a type checker will expect all
3270
+ instances to have a certain set of keys, where each key is
3271
+ associated with a value of a consistent type. This expectation
3272
+ is not checked at runtime.
3273
+
3274
+ Usage::
3275
+
3276
+ >>> class Point2D(TypedDict):
3277
+ ... x: int
3278
+ ... y: int
3279
+ ... label: str
3280
+ ...
3281
+ >>> a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
3282
+ >>> b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
3283
+ >>> Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
3284
+ True
3285
+
3286
+ The type info can be accessed by calling inspect.get_annotations(Point2D), and
3287
+ via the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
3288
+ TypedDict supports an additional equivalent form::
3289
+
3290
+ Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
3291
+
3292
+ By default, all keys must be present in a TypedDict. It is possible
3293
+ to override this by using the NotRequired and Required special forms::
3294
+
3295
+ class Point2D(TypedDict):
3296
+ x: int # the "x" key must always be present (Required is the default)
3297
+ y: NotRequired[int] # the "y" key can be omitted
3298
+
3299
+ This means that a Point2D TypedDict can have the "y" key omitted, but the "x" key must be present.
3300
+ Items are required by default, so the Required special form is not necessary in this example.
3301
+ In addition, the total argument to the TypedDict function can be used to make all items not required::
3302
+
3303
+ class Point2D(TypedDict, total=False):
3304
+ x: int
3305
+ y: int
3306
+
3307
+ This means that a Point2D TypedDict can have any of the keys omitted. A type
3308
+ checker is only expected to support a literal False or True as the value of
3309
+ the total argument. True is the default, and makes all items defined in the
3310
+ class body be required. The Required special form can be used to mark individual
3311
+ keys as required in a total=False TypedDict.
3312
+
3313
+ The ReadOnly special form can be used
3314
+ to mark individual keys as immutable for type checkers::
3315
+
3316
+ class DatabaseUser(TypedDict):
3317
+ id: ReadOnly[int] # the "id" key must not be modified
3318
+ username: str # the "username" key can be changed
3319
+
3320
+ See PEPs 589, 655, and 705 for more information.
3321
+ """
3322
+ if fields is _sentinel or fields is None:
3323
+ import warnings
3324
+
3325
+ if fields is _sentinel:
3326
+ deprecated_thing = "Failing to pass a value for the 'fields' parameter"
3327
+ else:
3328
+ deprecated_thing = "Passing `None` as the 'fields' parameter"
3329
+
3330
+ example = f"`{typename} = TypedDict({typename!r}, {{{{}}}})`"
3331
+ deprecation_msg = (
3332
+ "{name} is deprecated and will be disallowed in Python {remove}. "
3333
+ "To create a TypedDict class with 0 fields "
3334
+ "using the functional syntax, "
3335
+ "pass an empty dictionary, e.g. "
3336
+ ) + example + "."
3337
+ warnings._deprecated(deprecated_thing, message=deprecation_msg, remove=(3, 15))
3338
+ fields = {}
3339
+
3340
+ ns = {'__annotations__': dict(fields)}
3341
+ module = _caller()
3342
+ if module is not None:
3343
+ # Setting correct module is necessary to make typed dict classes pickleable.
3344
+ ns['__module__'] = module
3345
+
3346
+ td = _TypedDictMeta(typename, (), ns, total=total)
3347
+ td.__orig_bases__ = (TypedDict,)
3348
+ return td
3349
+
3350
+ _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
3351
+ TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)
3352
+
3353
+
3354
+ @_SpecialForm
3355
+ def Required(self, parameters):
3356
+ """Special typing construct to mark a TypedDict key as required.
3357
+
3358
+ This is mainly useful for total=False TypedDicts.
3359
+
3360
+ For example::
3361
+
3362
+ class Movie(TypedDict, total=False):
3363
+ title: Required[str]
3364
+ year: int
3365
+
3366
+ m = Movie(
3367
+ title='The Matrix', # type checker error if key is omitted
3368
+ year=1999,
3369
+ )
3370
+
3371
+ There is no runtime checking that a required key is actually provided
3372
+ when instantiating a related TypedDict.
3373
+ """
3374
+ item = _type_check(parameters, f'{self._name} accepts only a single type.')
3375
+ return _GenericAlias(self, (item,))
3376
+
3377
+
3378
+ @_SpecialForm
3379
+ def NotRequired(self, parameters):
3380
+ """Special typing construct to mark a TypedDict key as potentially missing.
3381
+
3382
+ For example::
3383
+
3384
+ class Movie(TypedDict):
3385
+ title: str
3386
+ year: NotRequired[int]
3387
+
3388
+ m = Movie(
3389
+ title='The Matrix', # type checker error if key is omitted
3390
+ year=1999,
3391
+ )
3392
+ """
3393
+ item = _type_check(parameters, f'{self._name} accepts only a single type.')
3394
+ return _GenericAlias(self, (item,))
3395
+
3396
+
3397
+ @_SpecialForm
3398
+ def ReadOnly(self, parameters):
3399
+ """A special typing construct to mark an item of a TypedDict as read-only.
3400
+
3401
+ For example::
3402
+
3403
+ class Movie(TypedDict):
3404
+ title: ReadOnly[str]
3405
+ year: int
3406
+
3407
+ def mutate_movie(m: Movie) -> None:
3408
+ m["year"] = 1992 # allowed
3409
+ m["title"] = "The Matrix" # type checker error
3410
+
3411
+ There is no runtime checking for this property.
3412
+ """
3413
+ item = _type_check(parameters, f'{self._name} accepts only a single type.')
3414
+ return _GenericAlias(self, (item,))
3415
+
3416
+
3417
+ class NewType:
3418
+ """NewType creates simple unique types with almost zero runtime overhead.
3419
+
3420
+ NewType(name, tp) is considered a subtype of tp
3421
+ by static type checkers. At runtime, NewType(name, tp) returns
3422
+ a dummy callable that simply returns its argument.
3423
+
3424
+ Usage::
3425
+
3426
+ UserId = NewType('UserId', int)
3427
+
3428
+ def name_by_id(user_id: UserId) -> str:
3429
+ ...
3430
+
3431
+ UserId('user') # Fails type check
3432
+
3433
+ name_by_id(42) # Fails type check
3434
+ name_by_id(UserId(42)) # OK
3435
+
3436
+ num = UserId(5) + 1 # type: int
3437
+ """
3438
+
3439
+ __call__ = _idfunc
3440
+
3441
+ def __init__(self, name, tp):
3442
+ self.__qualname__ = name
3443
+ if '.' in name:
3444
+ name = name.rpartition('.')[-1]
3445
+ self.__name__ = name
3446
+ self.__supertype__ = tp
3447
+ def_mod = _caller()
3448
+ if def_mod != 'typing':
3449
+ self.__module__ = def_mod
3450
+
3451
+ def __mro_entries__(self, bases):
3452
+ # We defined __mro_entries__ to get a better error message
3453
+ # if a user attempts to subclass a NewType instance. bpo-46170
3454
+ superclass_name = self.__name__
3455
+
3456
+ class Dummy:
3457
+ def __init_subclass__(cls):
3458
+ subclass_name = cls.__name__
3459
+ raise TypeError(
3460
+ f"Cannot subclass an instance of NewType. Perhaps you were looking for: "
3461
+ f"`{subclass_name} = NewType({subclass_name!r}, {superclass_name})`"
3462
+ )
3463
+
3464
+ return (Dummy,)
3465
+
3466
+ def __repr__(self):
3467
+ return f'{self.__module__}.{self.__qualname__}'
3468
+
3469
+ def __reduce__(self):
3470
+ return self.__qualname__
3471
+
3472
+ def __or__(self, other):
3473
+ return Union[self, other]
3474
+
3475
+ def __ror__(self, other):
3476
+ return Union[other, self]
3477
+
3478
+
3479
+ # Python-version-specific alias (Python 2: unicode; Python 3: str)
3480
+ Text = str
3481
+
3482
+
3483
+ # Constant that's True when type checking, but False here.
3484
+ TYPE_CHECKING = False
3485
+
3486
+
3487
+ class IO(Generic[AnyStr]):
3488
+ """Generic base class for TextIO and BinaryIO.
3489
+
3490
+ This is an abstract, generic version of the return of open().
3491
+
3492
+ NOTE: This does not distinguish between the different possible
3493
+ classes (text vs. binary, read vs. write vs. read/write,
3494
+ append-only, unbuffered). The TextIO and BinaryIO subclasses
3495
+ below capture the distinctions between text vs. binary, which is
3496
+ pervasive in the interface. For more precise types, define a custom
3497
+ Protocol.
3498
+ """
3499
+
3500
+ __slots__ = ()
3501
+
3502
+ @property
3503
+ @abstractmethod
3504
+ def mode(self) -> str:
3505
+ pass
3506
+
3507
+ @property
3508
+ @abstractmethod
3509
+ def name(self) -> str:
3510
+ pass
3511
+
3512
+ @abstractmethod
3513
+ def close(self) -> None:
3514
+ pass
3515
+
3516
+ @property
3517
+ @abstractmethod
3518
+ def closed(self) -> bool:
3519
+ pass
3520
+
3521
+ @abstractmethod
3522
+ def fileno(self) -> int:
3523
+ pass
3524
+
3525
+ @abstractmethod
3526
+ def flush(self) -> None:
3527
+ pass
3528
+
3529
+ @abstractmethod
3530
+ def isatty(self) -> bool:
3531
+ pass
3532
+
3533
+ @abstractmethod
3534
+ def read(self, n: int = -1) -> AnyStr:
3535
+ pass
3536
+
3537
+ @abstractmethod
3538
+ def readable(self) -> bool:
3539
+ pass
3540
+
3541
+ @abstractmethod
3542
+ def readline(self, limit: int = -1) -> AnyStr:
3543
+ pass
3544
+
3545
+ @abstractmethod
3546
+ def readlines(self, hint: int = -1) -> List[AnyStr]:
3547
+ pass
3548
+
3549
+ @abstractmethod
3550
+ def seek(self, offset: int, whence: int = 0) -> int:
3551
+ pass
3552
+
3553
+ @abstractmethod
3554
+ def seekable(self) -> bool:
3555
+ pass
3556
+
3557
+ @abstractmethod
3558
+ def tell(self) -> int:
3559
+ pass
3560
+
3561
+ @abstractmethod
3562
+ def truncate(self, size: int = None) -> int:
3563
+ pass
3564
+
3565
+ @abstractmethod
3566
+ def writable(self) -> bool:
3567
+ pass
3568
+
3569
+ @abstractmethod
3570
+ def write(self, s: AnyStr) -> int:
3571
+ pass
3572
+
3573
+ @abstractmethod
3574
+ def writelines(self, lines: List[AnyStr]) -> None:
3575
+ pass
3576
+
3577
+ @abstractmethod
3578
+ def __enter__(self) -> 'IO[AnyStr]':
3579
+ pass
3580
+
3581
+ @abstractmethod
3582
+ def __exit__(self, type, value, traceback) -> None:
3583
+ pass
3584
+
3585
+
3586
+ class BinaryIO(IO[bytes]):
3587
+ """Typed approximation of the return of open() in binary mode."""
3588
+
3589
+ __slots__ = ()
3590
+
3591
+ @abstractmethod
3592
+ def write(self, s: Union[bytes, bytearray]) -> int:
3593
+ pass
3594
+
3595
+ @abstractmethod
3596
+ def __enter__(self) -> 'BinaryIO':
3597
+ pass
3598
+
3599
+
3600
+ class TextIO(IO[str]):
3601
+ """Typed approximation of the return of open() in text mode."""
3602
+
3603
+ __slots__ = ()
3604
+
3605
+ @property
3606
+ @abstractmethod
3607
+ def buffer(self) -> BinaryIO:
3608
+ pass
3609
+
3610
+ @property
3611
+ @abstractmethod
3612
+ def encoding(self) -> str:
3613
+ pass
3614
+
3615
+ @property
3616
+ @abstractmethod
3617
+ def errors(self) -> Optional[str]:
3618
+ pass
3619
+
3620
+ @property
3621
+ @abstractmethod
3622
+ def line_buffering(self) -> bool:
3623
+ pass
3624
+
3625
+ @property
3626
+ @abstractmethod
3627
+ def newlines(self) -> Any:
3628
+ pass
3629
+
3630
+ @abstractmethod
3631
+ def __enter__(self) -> 'TextIO':
3632
+ pass
3633
+
3634
+
3635
+ def reveal_type[T](obj: T, /) -> T:
3636
+ """Ask a static type checker to reveal the inferred type of an expression.
3637
+
3638
+ When a static type checker encounters a call to ``reveal_type()``,
3639
+ it will emit the inferred type of the argument::
3640
+
3641
+ x: int = 1
3642
+ reveal_type(x)
3643
+
3644
+ Running a static type checker (e.g., mypy) on this example
3645
+ will produce output similar to 'Revealed type is "builtins.int"'.
3646
+
3647
+ At runtime, the function prints the runtime type of the
3648
+ argument and returns the argument unchanged.
3649
+ """
3650
+ print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr)
3651
+ return obj
3652
+
3653
+
3654
+ class _IdentityCallable(Protocol):
3655
+ def __call__[T](self, arg: T, /) -> T:
3656
+ ...
3657
+
3658
+
3659
+ def dataclass_transform(
3660
+ *,
3661
+ eq_default: bool = True,
3662
+ order_default: bool = False,
3663
+ kw_only_default: bool = False,
3664
+ frozen_default: bool = False,
3665
+ field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = (),
3666
+ **kwargs: Any,
3667
+ ) -> _IdentityCallable:
3668
+ """Decorator to mark an object as providing dataclass-like behavior.
3669
+
3670
+ The decorator can be applied to a function, class, or metaclass.
3671
+
3672
+ Example usage with a decorator function::
3673
+
3674
+ @dataclass_transform()
3675
+ def create_model[T](cls: type[T]) -> type[T]:
3676
+ ...
3677
+ return cls
3678
+
3679
+ @create_model
3680
+ class CustomerModel:
3681
+ id: int
3682
+ name: str
3683
+
3684
+ On a base class::
3685
+
3686
+ @dataclass_transform()
3687
+ class ModelBase: ...
3688
+
3689
+ class CustomerModel(ModelBase):
3690
+ id: int
3691
+ name: str
3692
+
3693
+ On a metaclass::
3694
+
3695
+ @dataclass_transform()
3696
+ class ModelMeta(type): ...
3697
+
3698
+ class ModelBase(metaclass=ModelMeta): ...
3699
+
3700
+ class CustomerModel(ModelBase):
3701
+ id: int
3702
+ name: str
3703
+
3704
+ The ``CustomerModel`` classes defined above will
3705
+ be treated by type checkers similarly to classes created with
3706
+ ``@dataclasses.dataclass``.
3707
+ For example, type checkers will assume these classes have
3708
+ ``__init__`` methods that accept ``id`` and ``name``.
3709
+
3710
+ The arguments to this decorator can be used to customize this behavior:
3711
+ - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
3712
+ ``True`` or ``False`` if it is omitted by the caller.
3713
+ - ``order_default`` indicates whether the ``order`` parameter is
3714
+ assumed to be True or False if it is omitted by the caller.
3715
+ - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
3716
+ assumed to be True or False if it is omitted by the caller.
3717
+ - ``frozen_default`` indicates whether the ``frozen`` parameter is
3718
+ assumed to be True or False if it is omitted by the caller.
3719
+ - ``field_specifiers`` specifies a static list of supported classes
3720
+ or functions that describe fields, similar to ``dataclasses.field()``.
3721
+ - Arbitrary other keyword arguments are accepted in order to allow for
3722
+ possible future extensions.
3723
+
3724
+ At runtime, this decorator records its arguments in the
3725
+ ``__dataclass_transform__`` attribute on the decorated object.
3726
+ It has no other runtime effect.
3727
+
3728
+ See PEP 681 for more details.
3729
+ """
3730
+ def decorator(cls_or_fn):
3731
+ cls_or_fn.__dataclass_transform__ = {
3732
+ "eq_default": eq_default,
3733
+ "order_default": order_default,
3734
+ "kw_only_default": kw_only_default,
3735
+ "frozen_default": frozen_default,
3736
+ "field_specifiers": field_specifiers,
3737
+ "kwargs": kwargs,
3738
+ }
3739
+ return cls_or_fn
3740
+ return decorator
3741
+
3742
+
3743
+ type _Func = Callable[..., Any]
3744
+
3745
+
3746
+ def override[F: _Func](method: F, /) -> F:
3747
+ """Indicate that a method is intended to override a method in a base class.
3748
+
3749
+ Usage::
3750
+
3751
+ class Base:
3752
+ def method(self) -> None:
3753
+ pass
3754
+
3755
+ class Child(Base):
3756
+ @override
3757
+ def method(self) -> None:
3758
+ super().method()
3759
+
3760
+ When this decorator is applied to a method, the type checker will
3761
+ validate that it overrides a method or attribute with the same name on a
3762
+ base class. This helps prevent bugs that may occur when a base class is
3763
+ changed without an equivalent change to a child class.
3764
+
3765
+ There is no runtime checking of this property. The decorator attempts to
3766
+ set the ``__override__`` attribute to ``True`` on the decorated object to
3767
+ allow runtime introspection.
3768
+
3769
+ See PEP 698 for details.
3770
+ """
3771
+ try:
3772
+ method.__override__ = True
3773
+ except (AttributeError, TypeError):
3774
+ # Skip the attribute silently if it is not writable.
3775
+ # AttributeError happens if the object has __slots__ or a
3776
+ # read-only property, TypeError if it's a builtin class.
3777
+ pass
3778
+ return method
3779
+
3780
+
3781
+ def is_protocol(tp: type, /) -> bool:
3782
+ """Return True if the given type is a Protocol.
3783
+
3784
+ Example::
3785
+
3786
+ >>> from typing import Protocol, is_protocol
3787
+ >>> class P(Protocol):
3788
+ ... def a(self) -> str: ...
3789
+ ... b: int
3790
+ >>> is_protocol(P)
3791
+ True
3792
+ >>> is_protocol(int)
3793
+ False
3794
+ """
3795
+ return (
3796
+ isinstance(tp, type)
3797
+ and getattr(tp, '_is_protocol', False)
3798
+ and tp != Protocol
3799
+ )
3800
+
3801
+
3802
+ def get_protocol_members(tp: type, /) -> frozenset[str]:
3803
+ """Return the set of members defined in a Protocol.
3804
+
3805
+ Example::
3806
+
3807
+ >>> from typing import Protocol, get_protocol_members
3808
+ >>> class P(Protocol):
3809
+ ... def a(self) -> str: ...
3810
+ ... b: int
3811
+ >>> get_protocol_members(P) == frozenset({'a', 'b'})
3812
+ True
3813
+
3814
+ Raise a TypeError for arguments that are not Protocols.
3815
+ """
3816
+ if not is_protocol(tp):
3817
+ raise TypeError(f'{tp!r} is not a Protocol')
3818
+ return frozenset(tp.__protocol_attrs__)
3819
+
3820
+
3821
+ def __getattr__(attr):
3822
+ """Improve the import time of the typing module.
3823
+
3824
+ Soft-deprecated objects which are costly to create
3825
+ are only created on-demand here.
3826
+ """
3827
+ if attr in {"Pattern", "Match"}:
3828
+ import re
3829
+ obj = _alias(getattr(re, attr), 1)
3830
+ elif attr in {"ContextManager", "AsyncContextManager"}:
3831
+ import contextlib
3832
+ obj = _alias(getattr(contextlib, f"Abstract{attr}"), 2, name=attr, defaults=(bool | None,))
3833
+ elif attr == "_collect_parameters":
3834
+ import warnings
3835
+
3836
+ depr_message = (
3837
+ "The private _collect_parameters function is deprecated and will be"
3838
+ " removed in a future version of Python. Any use of private functions"
3839
+ " is discouraged and may break in the future."
3840
+ )
3841
+ warnings.warn(depr_message, category=DeprecationWarning, stacklevel=2)
3842
+ obj = _collect_type_parameters
3843
+ else:
3844
+ raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")
3845
+ globals()[attr] = obj
3846
+ return obj